<?php

/**
 * 志汇活动报名高级版模块小程序接口定义
 *
 * @author 武汉志汇科技
 * @url http://bbs.we7.cc/
 */

defined('IN_IA') or exit('Access Denied');

class Zh_gjhdbmModuleWxapp extends WeModuleWxapp
{
    public function doPageTest()
    {
        global $_GPC, $_W;
        $errno = 0;
        $message = '返回消息';
        $data = array();
        return $this->result($errno, $message, $data);
    }

    //获取openid
    public function doPageOpenid()
    {
        global $_W, $_GPC;
        $res = pdo_get('zh_gjhdbm_system', array('uniacid' => $_W['uniacid']));
        $code = $_GPC['code'];
        $appid = $res['appid'];
        $secret = $res['appsecret'];
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $appid . "&secret=" . $secret . "&js_code=" . $code . "&grant_type=authorization_code";
        function httpRequest($url, $data = null)
        {
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
            if (!empty($data)) {
                curl_setopt($curl, CURLOPT_POST, 1);
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            //执行
            $output = curl_exec($curl);
            curl_close($curl);
            return $output;
        }

        $res = httpRequest($url);
        print_r($res);
    }


    //登录用户信息
    public function doPageLogin()
    {
        global $_GPC, $_W;
        $openid = $_GPC['openid'];
        $res = pdo_get('zh_gjhdbm_user', array('openid' => $openid, 'uniacid' => $_W['uniacid']));
        if ($openid and $openid != 'undefined') {
            if ($res) {
                $user_id = $res['id'];
                $data['openid'] = $_GPC['openid'];
                $data['img'] = $_GPC['img'];
                $data['name'] = $_GPC['name'];
                $res = pdo_update('zh_gjhdbm_user', $data, array('id' => $user_id));
                $user = pdo_get('zh_gjhdbm_user', array('openid' => $openid, 'uniacid' => $_W['uniacid']));
            } else {
                $data['openid'] = $_GPC['openid'];
                $data['img'] = $_GPC['img'];
                $data['name'] = $_GPC['name'];
                $data['uniacid'] = $_W['uniacid'];
                $data['join_time'] = time();
                $res2 = pdo_insert('zh_gjhdbm_user', $data);
                $user = pdo_get('zh_gjhdbm_user', array('openid' => $openid, 'uniacid' => $_W['uniacid']));
            }
            //判断是否已经实名
            $user['status'] = 0;
            if ($user['user_name']) {
                $user['status'] = 1;
            }
            echo json_encode($user);
        }
    }

    /**
     * 判断是否实名
     */
    public function doPageIsVerify()
    {
        global $_GPC, $_W;
        $openid = $_GPC['openid'];
        $user = pdo_get('zh_gjhdbm_user', array('openid' => $openid, 'uniacid' => $_W['uniacid']));
        if ($user) {
            //判断是否已经实名
            $data['code'] = 1;
            $data['message'] = '请求成功';
            $data['status'] = 0;
            if ($user['user_name']) {
                $data['status'] = 1;
            }
        } else {
            $data['code'] = 0;
            $data['message'] = '请求失败';
        }
        echo json_encode($data);
        exit;
    }

    /**
     * 某用户信息
     */
    public function doPageUserInfo()
    {
        global $_GPC;
        $user_id = intval($_GPC['user_id']);
        if (empty($user_id)) {
            $data['code'] = 0;
            $data['message'] = '系统繁忙';
            echo json_encode($data);
            exit;
        }
        $res = pdo_fetch("select * from " . tablename('zh_gjhdbm_user') . " where id = " . $user_id);
        if ($res) {
            if ($res['is_police'] == 0) {
                $res['tels'] = $tels = pdo_fetchall("select * from " . tablename('zh_gjhdbm_tel') . " where user_id = " . $user_id);
                $res['cars'] = $cars = pdo_fetchall("select * from " . tablename('zh_gjhdbm_car') . " where user_id = " . $user_id);
            }
            $read = pdo_fetchall("select *,FROM_UNIXTIME(add_time,'%Y%m%d%H%i%s') as title from " . tablename('zh_gjhdbm_message') . "where is_read = 0 and belong_id = " . $user_id);
            $res['read'] = count($read);
            $data['code'] = 1;
            $data['message'] = '操作成功';
            $data['result'] = $res;

        } else {
            $data['code'] = 0;
            $data['message'] = '操作失败';
        }
        echo json_encode($data);
    }

    /**
     * 普通用户实名认证、编辑
     */
    public function doPageVerifyUser()
    {
        global $_GPC;
        $info['user_id'] = $user_id = intval($_GPC['user_id']);
        $info['idcard'] = $idcard = trim($_GPC['idcard']);
        $info['user_name'] = $user_name = trim($_GPC['user_name']);
        $tels = array_filter(explode(';', $_GPC['tels']));
        $driving_nums = explode(';', $_GPC['driving_nums']);
        $car_nums = explode(';', $_GPC['car_nums']);
        $secure_companys = explode(';', $_GPC['secure_companys']);
        $codes = explode(';', $_GPC['codes']);

        if (empty($user_id)) {
            $data['code'] = 0;
            $data['message'] = '系统繁忙';
            echo json_encode($data);
            exit;
        }
        if (empty($idcard)) {
            $data['code'] = 0;
            $data['message'] = '身份证不能为空';
            echo json_encode($data);
            exit;
        }
        if (empty($user_name)) {
            $data['code'] = 0;
            $data['message'] = '姓名不能为空';
            echo json_encode($data);
            exit;
        }
        if (empty($tels)) {
            $data['code'] = 0;
            $data['message'] = '手机号不能为空';
            echo json_encode($data);
            exit;
        }
        $type = 1;
        $car_nums_a=str_replace(';','',$_GPC['car_nums']);
        if($car_nums_a){
            $type = 0;
        }

        /*
        $res = pdo_fetch("select * from " . tablename('zh_gjhdbm_user') . " where  idcard= '{$idcard}'");
        if ($res) {
            $data['code'] = 0;
            $data['message'] = '系统中已存在相同的身份信息';
            echo json_encode($data);
            exit;
        }*/
        
        //判断手机号是否再系统中存在
        foreach ($tels as $tel) {
            $res = pdo_fetch("select * from " . tablename('zh_gjhdbm_tel') . " where tel = " . $tel." and user_id != ".$user_id);
            if ($res) {
                $data['code'] = 0;
                $data['message'] = '手机号在系统中存在';
                echo json_encode($data);
                exit;
            }
        }
        $res = pdo_update('zh_gjhdbm_user', array('idcard' => $idcard, 'user_name' => $user_name,'type'=>$type), array('id' => $user_id));
        //判断手机号验证码的正确性
        $status = 0;
        foreach ($tels as $key=>$tel) {
            $telInfo = pdo_fetch("select * from ".tablename('zh_gjhdbm_tel')." where tel = ".$tel." and user_id = ".$user_id);
            if(empty($telInfo)){
                $codeInfo = pdo_fetch("select * from ".tablename('zh_gjhdbm_code')." where mobile = ".$tel);
                if($codeInfo) {
                    if ($codeInfo['is_used'] == 1) {
                        $data['code'] = 0;
                        $data['message'] = $tel.'验证码已失效';
                        $status = 1;
                        break;
                    }
                    if ($codeInfo['code'] != $codes[$key]) {
                        $data['code'] = 0;
                        $data['message'] = $tel.'验证码不正确';
                        $status = 1;
                        break;
                    }
                    if (time() > $codeInfo['expire']) {
                        $data['code'] = 0;
                        $data['message'] = $tel.'验证码已过期,请重新获取';
                        $status = 1;
                        break;
                    }
                }else{
                    $data['code'] = 0;
                    $data['message'] = '请获取验证码';
                    $status = 1;
                    break;
                }
            }
        }
       if($status == 0){
           pdo_delete('zh_gjhdbm_tel', array('user_id' => $user_id));
           foreach ($tels as $tel) {
               pdo_update('zh_gjhdbm_code', array('is_used' => 1), array('mobile' => $tel));
               $contactInfo = pdo_fetchall("select * from ".tablename('zh_gjhdbm_contact')." where contact_tel = ".$tel);
               foreach ($contactInfo as $contact){
                   pdo_update('zh_gjhdbm_contact',array('user_id'=>$user_id),array('contact_id'=>$contact['contact_id']));
               }
               //处理未实名但后台已经添加案件的情况，实名时处理手机号的绑定
               pdo_insert('zh_gjhdbm_tel', array('user_id' => $user_id, 'tel' => $tel));
           }
           if($type == 0){
               pdo_delete('zh_gjhdbm_car', array('user_id' => $user_id));
               foreach ($driving_nums as $key => $driving_num) {
                   pdo_insert('zh_gjhdbm_car', array('user_id' => $user_id, 'driving_num' => $driving_num, 'car_num' => $car_nums[$key], 'secure_company' => $secure_companys[$key]));
               }
           }


           $data['code'] = 1;
           $data['message'] = '操作成功';

           echo json_encode($data);
       }else{
           echo json_encode($data);
       }
    }

    /**
     * 交警实名认证
     */
    public function doPagePoliceVerify()
    {
        global $_GPC;
        $info['user_id'] = $user_id = intval($_GPC['user_id']);
        $info['tel'] = $tel = trim($_GPC['tel']);
        $info['code'] = $code = trim($_GPC['code']);
        $info['user_name'] = $user_name = trim($_GPC['user_name']);
        $info['police_num'] = $police_num = trim($_GPC['police_num']);

        if (empty($user_id)) {
            $data['code'] = 0;
            $data['message'] = '系统繁忙';
            echo json_encode($data);
            exit;
        }
        if (empty($user_name)) {
            $data['code'] = 0;
            $data['message'] = '姓名不能为空';
            echo json_encode($data);
            exit;
        }
        if (empty($tel)) {
            $data['code'] = 0;
            $data['message'] = '电话不能为空';
            echo json_encode($data);
            exit;
        }
        if (empty($police_num)) {
            $data['code'] = 0;
            $data['message'] = '警号不能为空';
            echo json_encode($data);
            exit;
        }
        if(empty($code)){
            $data['code'] = 0;
            $data['message'] = '验证码不能为空';
            echo json_encode($data);
            exit;
        }
        $codeInfo = pdo_fetch("select * from ".tablename('zh_gjhdbm_code')." where mobile = ".$tel);
        if($codeInfo){
            if($codeInfo['is_used'] == 1){
                $data['code'] = 0;
                $data['message'] = '验证码已失效';
                echo json_encode($data);
                exit;
            }
            if($codeInfo['code']!=$code){
                $data['code'] = 0;
                $data['message'] = '验证码不正确';
                echo json_encode($data);
                exit;
            }
            if(time()>$codeInfo['expire']){
                $data['code'] = 0;
                $data['message'] = '验证码已过期,请重新获取';
                echo json_encode($data);
                exit;
            }
            pdo_update('zh_gjhdbm_code',array('is_used'=>1),array('id'=>$codeInfo['id']));
            $res = pdo_update('zh_gjhdbm_user', array('link_tel' => $tel, 'user_name' => $user_name, 'police_num' => $police_num, 'is_police' => 2), array('id' => $user_id));
            if ($res) {
                $data['code'] = 1;
                $data['message'] = '操作成功';

            } else {
                $data['code'] = 0;
                $data['message'] = '操作失败';
            }
            echo json_encode($data);
        }else{
            $data['code'] = 0;
            $data['message'] = '请获取验证码';
            echo json_encode($data);
            exit;
        }


    }

    /**
     * 交警下发通知
     */
    public function doPageChangeMessage()
    {
        global $_GPC,$_W;
        $data['case_id'] = $case_id = intval($_GPC['case_id']);
        $data['message'] = $message = trim($_GPC['message']);
        $data['deal_id'] = $deal_id = intval($_GPC['deal_id']);
        $data['pic'] = $pic = trim($_GPC['pic']);
        $form_id = trim($_GPC['form_id']);
        $user_id = intval($_GPC['user_id']);

        $data['add_time'] = time();
        if (empty($case_id) || empty($deal_id) || empty($user_id)) {
            $notice['code'] = 0;
            $notice['message'] = '系统繁忙';
            echo json_encode($notice);
            exit;
        }

        if (empty($message)) {
            $notice['code'] = 0;
            $notice['message'] = '请填写通知内容';
            echo json_encode($notice);
            exit;
        }
        $system = pdo_get('zh_gjhdbm_system', array('uniacid' => $_W['uniacid']));
        $data['belong_id'] = $user_id;
        $res = pdo_insert('zh_gjhdbm_message', $data);
        //todo 接短信接口
        $contactInfo = pdo_fetch("select t.contact_tel,u.user_name from ".tablename('zh_gjhdbm_case')." as c left join ".tablename('zh_gjhdbm_contact')." as t on c.case_id = t.case_id left join ".tablename('zh_gjhdbm_user')." as u on u.id = t.user_id  where t.user_id = ".$user_id);
        if($contactInfo){
            $this->send_msg($contactInfo['contact_tel'],array('car'=>$contactInfo['user_name']),$system['tpl_id']);
        }
        //消息推送
//        $this->send_message($case_id,$form_id,$deal_id);

        if ($res) {
            $notice['code'] = 1;
            $notice['message'] = '通知成功';

        } else {
            $notice['code'] = 0;
            $notice['message'] = '通知失败';
        }
        echo json_encode($notice);
    }
    
    public function doPageGetMessage()
    {
        global $_GPC;
        
        $user_id = intval($_GPC['user_id']);
        
        if (empty($user_id)) {
            $notice['code'] = 0;
            $notice['message'] = '选择用户';
            echo json_encode($notice);
            exit;
        }
        $res = pdo_fetchall("select *,FROM_UNIXTIME(add_time,'%Y%m%d%H%i%s') as title from " . tablename('zh_gjhdbm_message') . "where belong_id = " . $user_id);
        if ($res) {
            $notice['code'] = 1;
            $notice['message'] = '获取成功';
            $notice['list'] = $res;
    
        } else {
            $notice['code'] = 1;
            $notice['message'] = '数据为空';
            $notice['list'] = array();
        }
        echo json_encode($notice);
    }
    /**
     * 修改已读的状态
     */
    public function doPageReadMessage(){
        global $_GPC;
        $id = intval($_GPC['id']);
        if (empty($id)) {
            $notice['code'] = 0;
            $notice['message'] = '系统繁忙';
            echo json_encode($notice);
            exit;
        }
        $info = pdo_fetch("select * from ".tablename('zh_gjhdbm_message')." where id = ".$id);
        if($info){
            $res = pdo_update('zh_gjhdbm_message',array('is_read'=>1),array('id'=>$id));
            if ($res) {
                $notice['code'] = 1;
                $notice['message'] = '修改成功';
            } else {
                $notice['code'] = 0;
                $notice['message'] = '修改失败';
            }
        }else{
            $notice['code'] = 0;
            $notice['message'] = '不存在该消息';
        }
        echo json_encode($notice);
    }

    /**
     * 修改案件进度
     */
    public function doPageChangeProgress()
    {
        global $_GPC,$_W;
        $case_id = $_GPC['case_id'];
        if (empty($case_id)) {
            $data['code'] = 0;
            $data['message'] = '系统繁忙';
            echo json_encode($data);
            exit;
        }
        $sub_status = intval(empty($_GPC['sub_status'])?0:$_GPC['sub_status']);
        $res = pdo_update('zh_gjhdbm_case', array('sub_status'=>$sub_status), array('case_id' => $case_id));
        if ($res) {
            //todo 接短信接口
            $contactInfo = pdo_fetchall("select t.contact_tel,u.user_name from ".tablename('zh_gjhdbm_contact')." as t left join ".tablename('zh_gjhdbm_user')." as u on u.id = t.user_id  where t.case_id = ".$case_id);
            $system = pdo_get('zh_gjhdbm_system', array('uniacid' => $_W['uniacid']));
            $case_info = pdo_fetch("select * from ".tablename('zh_gjhdbm_case')." where case_id = ".$case_id);
            $type = $this->status($case_info['sub_status']);
            foreach ($contactInfo as $contact){
                $this->send_msg($contact['contact_tel'],array('status'=>$type,'remark'=>$case_info['event_num']),$system['tpl_id2']);
            }
            $data['code'] = 1;
            $data['message'] = '修改成功';
        } else {
            $data['code'] = 0;
            $data['message'] = '修改失败';
        }
        echo json_encode($data);
    }

    /**
     * 根据手机号 获取车牌信息
     */
    public function doPageGetCarInfo()
    {
        global $_GPC;
        $tel = trim($_GPC['tel']);
        $user_id = intval($_GPC['user_id']);
        $type = intval($_GPC['type'])?intval($_GPC['type']):0;

        if (empty($tel)) {
            $data['code'] = 0;
            $data['message'] = '手机号不能为空';
            echo json_encode($data);
            exit;
        }
        if (empty($user_id)) {
            $data['code'] = 0;
            $data['message'] = '系统繁忙';
            echo json_encode($data);
            exit;
        }
        if($type != 0 ){
            $is_in = pdo_fetch("select * from ".tablename('zh_gjhdbm_tel')." where user_id = ".$user_id ." and tel = '".$tel."'");
            if(!$is_in){
                $data['code'] = 0;
                $data['message'] = '手机号输入不正确';
                echo json_encode($data);
                exit;
            }
        }
        $telInfo = pdo_fetch("select * from " . tablename('zh_gjhdbm_tel') . " where tel = '{$tel}'");
        if ($telInfo) {
            $user_id = $telInfo['user_id'];
            $userInfo = pdo_fetch("select user_name,`name` ,`type` from " . tablename('zh_gjhdbm_user') . " where id = " . $user_id);
            $carInfo = pdo_fetchall("select car_num from " . tablename('zh_gjhdbm_car') . "where user_id = " . $user_id);
            if ($userInfo) {
                $result = array(
                    'user_name' => $userInfo['user_name'],
                    'name' => $userInfo['name'],
                    'type' => $userInfo['type'],
                    'carInfo' => $carInfo
                );
                $data['code'] = 1;
                $data['message'] = '操作成功';
                $data['result'] = $result;
            } else {
                $data['code'] = 1;
                $data['message'] = '操作成功';
                $data['result'] = array();
            }
        } else {
            $data['code'] = 0;
            $data['message'] = '系统中不存在该手机号';
        }
        echo json_encode($data);


    }
    /**
     * 绑定案件
     */
    public function doPageBindCase(){
        global $_GPC;
        $case_id = $_GPC['case_id'];
        if (empty($case_id)) {
            $data['code'] = 0;
            $data['message'] = '系统繁忙';
            echo json_encode($data);
            exit;
        }
        $contact_index = array("甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸");

        $contact_name = trim($_GPC['contact_name']);
        $plate_num = trim($_GPC['plate_num']);
        $contact_tel = trim($_GPC['contact_tel']);
        $kind = intval($_GPC['kind']);
        if (empty($contact_name)||empty($plate_num)||empty($contact_tel)) {
            $data['code'] = 0;
            $data['message'] = '信息不完整';
            echo json_encode($data);
            exit;
        }
        $caseall = pdo_fetchall("select * from ".tablename('zh_gjhdbm_contact')." where case_id = ".$case_id);
        $count = count($caseall);
        $type = $contact_index[$count];
        $user =  pdo_fetch("select * from ".tablename('zh_gjhdbm_tel')." where tel = ".$contact_tel);
        if($user){
            $contact_info = array(
                "case_id" => $case_id,
                "contact_name" => $contact_name,
                "contact_tel" => $contact_tel,
                "plate_num" => $plate_num,
                "type" => $type,
                "user_id"=>$user['user_id'],
                "kind"=>$kind
            );
           $res =  pdo_insert('zh_gjhdbm_contact', $contact_info);
            if($res){
                $data['code'] = 1;
                $data['message'] = '绑定成功';
            } else {
                $data['code'] = 0;
                $data['message'] = '绑定失败';
            }

        }else{
            $data['code'] = 0;
            $data['message'] = '手机号不正确';
        }
        echo json_encode($data);
        exit;
    }
    /**
     * 交警修改通过编号添加的案件信息
     */
    public function doPageEditCase(){
        global $_GPC,$_W;
        $case_id = $_GPC['case_id'];
        $happen_time = trim($_GPC['happen_time']);
        $address = trim($_GPC['address']);
        if (empty($case_id)) {
            $data['code'] = 0;
            $data['message'] = '系统繁忙';
            echo json_encode($data);
            exit;
        }
        $caseInfo = pdo_fetch("select * from ".tablename('zh_gjhdbm_case')." where case_id = ".$case_id." and method = 2");
        if($caseInfo){
            $res = pdo_update('zh_gjhdbm_case',array('happen_time'=>$happen_time,'address'=>$address),array('case_id'=>$case_id));
            if($res){
                $data['code'] = 1;
                $data['message'] = '修改成功';
            } else {
                $data['code'] = 0;
                $data['message'] = '修改失败';
            }
        }else{
            $data['code'] = 0;
            $data['message'] = '修改失败';
        }
        echo json_encode($data);
        exit;

    }
    /**
     * 添加案件
     */
    public function doPageAddCase()
    {
        global $_GPC,$_W;
        $info['apply_id'] = $apply_id = $_GPC['user_id'];

        $user = pdo_get('zh_gjhdbm_user', array('id' => $apply_id));
        if ($user) {
            //判断是否已经实名
            $user_name = $user['user_name'];
            if ($user_name) {
                $info['address'] = $address = trim($_GPC['address']);
                $info['address_descript'] = $descript = trim($_GPC['descript']);
                $info['case_type'] = $case_type = $_GPC['case_type'] ? $_GPC['case_type'] : 0;
                $info['acc_pic'] = $acc_pic = htmlspecialchars_decode(trim($_GPC['acc_pic']));
                $info['add_time'] = $add_time = time();
                $info['form_id'] = $_GPC['formId'];
                $info['is_high_speed'] = $is_high_speed = $_GPC['is_high_speed'];
                $info['is_secure'] = $is_secure = $_GPC['is_secure'];
                $info['event_num'] = trim($_GPC['event_num'])?trim($_GPC['event_num']):date('YmdHis', $add_time);
                $info['method'] = $method = $_GPC['method'];

                $all_data = json_decode($acc_pic);
                $contact = array_filter(explode(';', $_GPC['contact']));
                $tel = array_filter(explode(';', $_GPC['tel']));
                $plate_num = array_filter(explode(';', $_GPC['plate_num']));
                $type = array_filter(explode(';', $_GPC['type']));
                $kind = array_filter(explode(';',$_GPC['kind']));
                if (empty($apply_id)||empty($method)) {
                    $data['code'] = 0;
                    $data['message'] = '系统繁忙';
                    echo json_encode($data);
                    exit;
                }

                if (empty($address)) {
                    $data['code'] = 0;
                    $data['message'] = '定位地址不能为空';
                    echo json_encode($data);
                    exit;
                }
                if (empty($case_type)) {
                    $data['code'] = 0;
                    $data['message'] = '事故类型不能为空';
                    echo json_encode($data);
                    exit;
                }
                if (empty($contact[0])) {
                    $data['code'] = 0;
                    $data['message'] = '联系人不能为空';
                    echo json_encode($data);
                    exit;
                }
                if (empty($tel[0])) {
                    $data['code'] = 0;
                    $data['message'] = '联系电话不能为空';
                    echo json_encode($data);
                    exit;
                }
                if (empty($plate_num[0])) {
                    $data['code'] = 0;
                    $data['message'] = '牌照不能为空';
                    echo json_encode($data);
                }
                if($method == 2){
                    $link_tel = trim($_GPC['link_tel']);

                    $info['event_num'] = $event_num = trim($_GPC['event_num']);
                    $info['happen_time'] = $happen_time = trim($_GPC['happen_time']);
                    $info['status'] = 1;
                    $info['sub_status'] = 1;
                    $info['is_recieve'] = 1;

                    if(empty($event_num)){
                        $data['code'] = 0;
                        $data['message'] = '事故编号不能为空';
                        echo json_encode($data);
                        exit;
                    }
                    if(empty($happen_time)){
                        $data['code'] = 0;
                        $data['message'] = '事故时间不能为空';
                        echo json_encode($data);
                        exit;
                    }
                    $police =  pdo_fetch("select * from ".tablename('zh_gjhdbm_user')." where link_tel = '".$link_tel."'");
                    if(empty($police)){
                        $data['code'] = 0;
                        $data['message'] = '交警电话输入错误';
                        echo json_encode($data);
                        exit;
                    }
                    $info['deal_id'] = $police['id'];
                }else{
                    $info['event_num'] = $this->createEventNum();
                    $info['happen_time'] = $happen_time = time();

                }

                $res = pdo_insert('zh_gjhdbm_case', $info);
                if ($res) {
                    $case_id = pdo_insertid();
                    if($case_id&&$method == 2){
                        $system = pdo_get('zh_gjhdbm_system', array('uniacid' => $_W['uniacid']));
                        $this->send_msg($link_tel,array('time'=>$happen_time,'address'=>$info['address'],'type'=>$case_type),$system['tpl_id1']);
                    }
                    //图片
                    foreach ($all_data as $key => $value) {
                        $pic = array(
                            'case_id' => $case_id,
                            'type' => $value->type,
                            'url' => $value->url
                        );
                        pdo_insert('zh_gjhdbm_pic', $pic);
                    }

                    //添加联系人信息
                    foreach ($contact as $key => $contact_name) {
                        $user =  pdo_fetch("select * from ".tablename('zh_gjhdbm_tel')." where tel = ".$tel[$key]);
                        $contact_info = array(
                            "case_id" => $case_id,
                            "contact_name" => $contact_name,
                            "contact_tel" => $tel[$key],
                            "plate_num" => $plate_num[$key],
                            "type" => $type[$key],
                            "user_id"=>$user['user_id'],
                            "kind" => $kind[$key],
                        );
                        pdo_insert('zh_gjhdbm_contact', $contact_info);
                    }
                    $data['code'] = 1;
                    $data['message'] = '添加成功';
                } else {
                    $data['code'] = 0;
                    $data['message'] = '添加失败';
                }
                echo json_encode($data);
                exit;
            } else {
                $data['code'] = 2;
                $data['message'] = '该用户未实名';
                echo json_encode($data);
                exit;
            }
        } else {
            $data['code'] = 0;
            $data['message'] = '添加失败';
            echo json_encode($data);
            exit;
        }

    }
    /**
     * 生成事故编号
     */
    public function createEventNum(){
        $time = date('Ymd', time());
        //获取今天的案件个数
        $todaycase = pdo_fetchall("select * from ".tablename('zh_gjhdbm_case')." where FROM_UNIXTIME(add_time,'%Y%m%d') = ".$time);
        $count = count($todaycase)+1;
        return $time.'50'.$count;
    }
    /**
     * 交警结案
     */
    public function doPageEndCase(){
        global $_GPC,$_W;
        $case_id = intval($_GPC['case_id']);
        $info['end_pic'] = $end_pic = trim($_GPC['end_pic']);
        $info['content'] = $content = trim($_GPC['content']);
        $info['status'] = 2;
        $info['end_time'] = time();
        if(empty($case_id)){
            $data['code'] = 0;
            $data['message'] = '系统繁忙';
            echo json_encode($data);
            exit;
        }
        $res =  pdo_update('zh_gjhdbm_case',$info,array('case_id'=>$case_id));
        if($res){
            $case_info = pdo_fetch("select * from ".tablename('zh_gjhdbm_case')." where case_id = ".$case_id);
            //获取所有事故方
            $contact_info = pdo_fetchall("select * from ".tablename('zh_gjhdbm_contact')." where case_id = ".$case_id);
            $system = pdo_get('zh_gjhdbm_system', array('uniacid' => $_W['uniacid']));
            foreach ($contact_info as $contact){
                $this->send_msg($contact['contact_tel'],array('status'=>'已结案','remark'=>$case_info['event_num']),$system['tpl_id2']);
            }
            $data['code'] = 1;
            $data['message'] = '结案成功';
        } else {
            $data['code'] = 0;
            $data['message'] = '结案失败';
        }
        echo json_encode($data);
        exit;
    }
    /**
     * 我的案件
     * user_id 用户编号
     * status 状态 -1全部  0待立案 1处理中 2已结案
     * status 状态 -1全部  0未接案件 1处理中 2已结案RFZMTtWptUR04nGxYRuQWOhjOTPjP4ZK25eOMg复制
     */
    public function doPageCaseList()
    {
        global $_GPC;
        $apply_id = $_GPC['user_id'] ? $_GPC['user_id'] : 0;
        $type = $_GPC['type'] ? $_GPC['type'] : 0;
        $user = pdo_get('zh_gjhdbm_user', array('id' => $apply_id));
        if ($user) {
            //判断是否已经实名
            $user_name = $user['user_name'];
            if ($user_name) {
                if ($user['is_police'] == 2) {
                    $data['code'] = 0;
                    $data['message'] = '您的身份正在审核中';
                    echo json_encode($data);
                    exit;
                }
                $status = $_GPC['status'] ? $_GPC['status'] : 0;
                $keyword = trim($_GPC['keyword']);
                if (empty($apply_id)) {
                    $data['code'] = 0;
                    $data['message'] = '系统繁忙';
                    echo json_encode($data);
                    exit;
                }
                $where = 'c.is_delete = 0 ';
                if($user['is_police'] == 1&&$type==0){
                    if ($status == 0) {//未接案件
                        $where .= " and c.is_recieve = 0 " ;
                    }elseif($status != -1){
                        $where .= " and c.status = " . $status;
                    }
                    $where .= " and c.deal_id = " . $apply_id;
                    $res = array();
                    $caseList  = pdo_fetchall("select c.* ,FROM_UNIXTIME(c.add_time,'%Y-%m-%d %H:%i:%s') as add_time,FROM_UNIXTIME(c.end_time,'%Y-%m-%d %H:%i:%s') as end_time from " . tablename('zh_gjhdbm_case') . " as c where " . $where.' order by c.case_id desc' );
                    foreach ($caseList as $case){
                        $info = pdo_fetch("select * from ".tablename('zh_gjhdbm_contact')." where case_id = ".$case['case_id']." and contact_tel like '%{$keyword}%'");
                        if($info){
                            $res[] = $case;
                        }
                    }
                }else{
                    if ($status != -1) {
                        $where .= " and c.status = " . $status;
                    }
                    if ($keyword) {
//                        $where .= " and (((c.apply_id = " . $apply_id." or t.user_id = ".$apply_id.") and (c.method = 1 or c.method = 3)) or (c.method = 2))";
                        $where .= " and c.event_num like '%".$keyword."%' " ;
                    }else{
                        $where .= " and (c.apply_id = " . $apply_id." or t.user_id = ".$apply_id.")";
                    }
                    $res = pdo_fetchall("select c.* ,FROM_UNIXTIME(c.add_time,'%Y-%m-%d %H:%i:%s') as add_time,FROM_UNIXTIME(c.end_time,'%Y-%m-%d %H:%i:%s') as end_time,d.user_name,d.link_tel from " . tablename('zh_gjhdbm_case') . " as c left join ".tablename('zh_gjhdbm_contact')." as t on c.case_id = t.case_id left join " . tablename('zh_gjhdbm_user') . " as d on c.deal_id = d.id where " . $where . "  group by c.case_id order by add_time desc ");
                }
                foreach ($res as $key => $item) {
                    $contacts = pdo_fetchall("select * from " . tablename('zh_gjhdbm_contact') . " where case_id = " . $item['case_id']);
                    foreach ($contacts as $contact){
                        if($contact['user_id'] == $apply_id||$item['apply_id'] == $apply_id){
                             $res[$key]['is_show'] = 1;
                             break;
                        }else{
                            $res[$key]['is_show'] = 0;
                        }
                    }
                    $res[$key]['contact_info'] = $contacts;
                }
                if ($res) {
                    $data['code'] = 1;
                    $data['message'] = '操作成功';
                    $data['result'] = $res;
                } else {
                    $data['code'] = 1;
                    $data['message'] = '操作成功';
                    $data['result'] = array();
                }
                echo json_encode($data);
            } else {
                $data['code'] = 2;
                $data['message'] = '该用户未实名';
                echo json_encode($data);
                exit;
            }
        } else {
            $data['code'] = 0;
            $data['message'] = '操作失败';
            echo json_encode($data);
            exit;
        }

    }

    /**
     * 交警接管案件
     */
    public function doPageReciveCase()
    {
        global $_GPC,$_W;
        $case_id = $_GPC['case_id'];
        if (empty($case_id)) {
            $data['code'] = 0;
            $data['message'] = '系统繁忙';
            echo json_encode($data);
            exit;
        }
        $res = pdo_update('zh_gjhdbm_case', array('status' =>1,'sub_status'=>1 ,'is_recieve'=>1), array('case_id' => $case_id));
        if ($res) {
            $case_info = pdo_fetch("select * from ".tablename('zh_gjhdbm_case')." where case_id = ".$case_id);
            //获取所有事故方
            $contact_info = pdo_fetchall("select * from ".tablename('zh_gjhdbm_contact')." where case_id = ".$case_id);
            $system = pdo_get('zh_gjhdbm_system', array('uniacid' => $_W['uniacid']));
            if($case_info){
                $type = $this->status($case_info['sub_status']);
            }
            foreach ($contact_info as $contact){
                $this->send_msg($contact['contact_tel'],array('status'=>$type,'remark'=>$case_info['event_num']),$system['tpl_id2']);
            }
            $data['code'] = 1;
            $data['message'] = '接管成功';
        } else {
            $data['code'] = 0;
            $data['message'] = '接管失败';
        }
        echo json_encode($data);
    }
   function status($sub_status){
       switch ($sub_status){
           case 1:
               $type = '调查处理中';
               break;
           case 2:
               $type = '技术鉴定中';
               break;
           case 3:
               $type = '下发认证书';
               break;
           default:
               $type = '调查处理中';
               break;
       }
       return $type;
   }
    /**
     * 案件详情
     */
    public function doPageCaseDetail()
    {
        global $_GPC;
        $case_id = $_GPC['case_id'];
        $caseInfo = pdo_fetch("select * from " . tablename('zh_gjhdbm_case') . " where case_id = " . $case_id);
        if ($caseInfo) {
            //获取事故图片
            $caseInfo['pic'] = pdo_fetchall("select * from " . tablename('zh_gjhdbm_pic') . " where case_id = " . $case_id);
            $contacts = pdo_fetchall("select * from " . tablename('zh_gjhdbm_contact') . " where case_id = " . $case_id);
            //根据手机号查询用户
            foreach ($contacts as $key => $contact) {
                $caseInfo['info'][$key]['kind'] = $contact['kind'];
                $caseInfo['info'][$key]['type'] = $contact['type'];
                $caseInfo['info'][$key]['contact_tel'] = $contact['contact_tel'];
                $telInfo = pdo_fetch("select * from " . tablename('zh_gjhdbm_tel') . " where tel = " . $contact['contact_tel']);
                $user_id = $telInfo['user_id'];
                $userInfo = pdo_fetch("select user_name,idcard from " . tablename('zh_gjhdbm_user') . " where id = " . $user_id);
                $caseInfo['info'][$key]['user_name'] = '';
                $caseInfo['info'][$key]['idcard'] = '';
                if ($userInfo) {
                    $caseInfo['info'][$key]['user_name'] = $userInfo['user_name'];
                    $caseInfo['info'][$key]['idcard'] = $userInfo['idcard'];
                }
                $plate_num = $contact['plate_num'];
                $carInfo = pdo_fetch("select * from " . tablename('zh_gjhdbm_car') . " where car_num = '" . $plate_num . "'"." and user_id = ".$user_id);
                $caseInfo['info'][$key]['car_num'] = '';
                $caseInfo['info'][$key]['driving_num'] = '';
                $caseInfo['info'][$key]['secure_company'] = '';
                if ($carInfo) {
                    $caseInfo['info'][$key]['id'] = $user_id;
                    $caseInfo['info'][$key]['car_num'] = $carInfo['car_num'];
                    $caseInfo['info'][$key]['driving_num'] = $carInfo['driving_num'];
                    $caseInfo['info'][$key]['secure_company'] = $carInfo['secure_company'];
                }else{
                    $caseInfo['info'][$key]['id'] = '';
                    $caseInfo['info'][$key]['car_num'] = '';
                    $caseInfo['info'][$key]['driving_num'] = '';
                    $caseInfo['info'][$key]['secure_company'] = '';
                }
            }
            $data['code'] = 1;
            $data['message'] = '操作成功';
            $data['result'] = $caseInfo;
        } else {
            $data['code'] = 0;
            $data['message'] = '操作失败';
        }
        echo json_encode($data);
    }

    /**
     * 某案件的证书
     */
    public function doPageCaseCert()
    {
        global $_GPC;
        $case_id = $_GPC['case_id'];
        if (empty($case_id)) {
            $data['code'] = 0;
            $data['message'] = '系统繁忙';
            echo json_encode($data);
            exit;
        }
        $res = pdo_fetch("select content,end_pic from " . tablename('zh_gjhdbm_case') . " where case_id = " . $case_id);
        if ($res) {
            $data['code'] = 1;
            $data['message'] = '获取成功';
            $data['result'] = $res;
        } else {
            $data['code'] = 0;
            $data['message'] = '获取失败';
        }
        echo json_encode($data);
    }

    /**
     * 文章列表
     */
    public function doPageArticle()
    {
        $res = pdo_fetchall("select * from " . tablename('zh_gjhdbm_article') . " where is_delete = 0");
        if ($res) {
            $data['code'] = 1;
            $data['message'] = '获取成功';
            $data['result'] = $res;
        } else {
            $data['code'] = 0;
            $data['message'] = '获取失败';
        }
        echo json_encode($data);
    }

    /**
     * 文章详情
     */
    public function doPageArticleDetail()
    {
        global $_GPC;
        $article_id = $_GPC['article_id'];
        if (empty($article_id)) {
            $data['code'] = 0;
            $data['message'] = '系统繁忙';
            echo json_encode($data);
            exit;
        }
        $res = pdo_fetch("select * from " . tablename('zh_gjhdbm_article') . " where article_id = " . $article_id);
        if ($res) {
            $data['code'] = 1;
            $data['message'] = '获取成功';
            $data['result'] = $res;
        } else {
            $data['code'] = 1;
            $data['message'] = '获取成功';
            $data['result'] = array();
        }
        echo json_encode($data);

    }

    /**
     * 短信验证码
     */
    public function doPageSendMsg(){
        global $_GPC;
        $mobile = $_GPC['mobile'];
        if(empty($mobile)){
            $data['code'] = 0;
            $data['message'] = '系统繁忙';
            echo json_encode($data);
            exit;
        }
        $code = $this->create_random(6);
        $this->send_msg($mobile,array('code'=>$code),'SMS_143714446');
        $res = pdo_fetch("select * from ".tablename('zh_gjhdbm_code')." where mobile = ".$mobile);
        if($res){
            pdo_update('zh_gjhdbm_code',array('code'=>$code,'expire'=>time()+2*3600,'is_used'=>0),array('id'=>$res['id']));
        }else{
            pdo_insert('zh_gjhdbm_code',array('mobile'=>$mobile,'code'=>$code,'expire'=>time()+2*3600,'is_used'=>0));
        }
        $data['code'] = 1;
        $data['message'] = '获取成功';
        echo json_encode($data);

    }
    //创建随机数
    function create_random($length, $char_str = '0123456789')
    {
        $hash = '';
        $chars = $char_str;
        $max = strlen($chars);
        for ($i = 0; $i < $length; $i++) {
            $hash .= substr($chars, (rand(0, 1000) % $max), 1);
        }
        return $hash;
    }

//短信验证码
    function send_msg($mobile, $data,$tpl_id) {
        global $_W;
        $res = pdo_get('zh_gjhdbm_system', array('uniacid' => $_W['uniacid']));
        include_once IA_ROOT . '/addons/zh_gjhdbm/ventor/dayu/SignatureHelper.php';
        $params = array ();
        $accessKeyId = $res['sms_key'];
        $accessKeySecret = $res['sms_secret'];
        $params["PhoneNumbers"] = $mobile;
        $params["SignName"] = $res['sign_name'];
        $params["TemplateCode"] = $tpl_id;
        $params['TemplateParam'] = $data;
        if(!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
            $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
        }
        $helper = new  \Aliyun\DySDKLite\SignatureHelper();
        $content = $helper->request(
            $accessKeyId,
            $accessKeySecret,
            "dysmsapi.aliyuncs.com",
            array_merge($params, array(
                "RegionId" => "cn-hangzhou",
                "Action" => "SendSms",
                "Version" => "2017-05-25",
            ))
        );
        file_put_contents(IA_ROOT . '/msg.log', json_decode($content), FILE_APPEND);
        return $content;
    }

    /**
     * 案件消息推送
     */
     function send_message($case_id,$form_id,$user_id){
         //交警
        $dealInfo = pdo_fetch("select u.openid,u.name,u.user_name,u.link_tel,c.event_num,c.status,c.sub_status from " . tablename('zh_gjhdbm_case') . " as c  left join " . tablename('zh_gjhdbm_user') . " as u on c.deal_id = u.id  where c.case_id = " . $case_id);
        if($dealInfo){
          if($dealInfo['status']==1){
              $status_txt = $this->status($dealInfo['sub_status']);
          }else{
              $status_txt = '已结案';
          }
        }
        //事故方
        $all_ac = pdo_fetch("select u.openid,u.name,u.user_name,u.uniacid from  ".tablename('zh_gjhdbm_user')." as u  where u.id = ".$user_id);
        $this->push_message($all_ac,$form_id,$status_txt,$dealInfo);

    }


    function push_message($userInfo,$form_id,$status_txt,$dealInfo){
        $uniacid = $userInfo['uniacid'];
        $access_token = $this->message_access_token($uniacid);
        $res = pdo_get('zh_gjhdbm_system', array('uniacid' => $uniacid));

        $formwork = array(
            "touser" => $userInfo['openid'],
            "template_id" => $res["tid2"],
            "form_id" => $form_id,
            "data" => array(
                "keyword1" => array(
                    "value" => $userInfo['user_name'],
                    "color" => "#173177"
                ),
                "keyword2" => array(
                    "value" => $dealInfo['event_num'],
                    "color" => "#173177"
                ),
                "keyword3" => array(
                    "value" => $status_txt,
                    "color" => "#173177"
                ),
                "keyword4" => array(
                    "value" => $dealInfo['user_name'],
                    "color" => "#173177"
                ),
                "keyword5" => array(
                    "value" => $dealInfo['link_tel'],
                    "color" => "#173177"
                )
            )
        );
        $res = json_encode($formwork);

        $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" . $access_token . "";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $res);
        $data = curl_exec($ch);
        curl_close($ch);
        file_put_contents(IA_ROOT . '/ddddddddddddd.log',json_encode($data), FILE_APPEND);
        return $data;
    }


    function message_access_token($uniacid) {
        $res = pdo_get('zh_gjhdbm_system', array('uniacid' => $uniacid));
        $appid = $res['appid'];
        $secret = $res['appsecret'];
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret . "";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $data = curl_exec($ch);
        curl_close($ch);
        $data = json_decode($data, true);
        return $data['access_token'];
    }

//上传图片
    public function doPageUpload()
    {
        global $_W, $_GPC;
        $uptypes = array('image/jpg', 'image/jpeg', 'image/png', 'image/pjpeg', 'image/gif', 'image/bmp', 'image/x-png');
        $max_file_size = 2000000;     //上传文件大小限制, 单位BYTE
        $destination_folder = "../attachment/upload/"; //上传文件路径
        if (!is_uploaded_file($_FILES["upfile"]['tmp_name'])) {
            $data['path'] = '';
            $data['code'] = 0;
            $data['message'] = '图片不存在！';
            echo json_encode($data);
            exit;
        }
        $file = $_FILES["upfile"];
        if ($max_file_size < $file["size"]) {
            $data['path'] = '';
            $data['code'] = 0;
            $data['message'] = '文件过大！';
            echo json_encode($data);
            exit;
        }
        //兼容处理部分安卓机是字节流类型
        if($file['type'] == 'application/octet-stream'){
            $file['type'] = 'image/'. pathinfo($file['name'],PATHINFO_EXTENSION);
        }
        if (!in_array($file["type"], $uptypes)) {
            $data['path'] = '';
            $data['code'] = 0;
            $data['message'] = '文件类型不符！';
            echo json_encode($data);
            exit;
        }
        $filename = $file["tmp_name"];
        $image_size = getimagesize($filename);
        $pinfo = pathinfo($file["name"]);
        $ftype = $pinfo['extension'];
        $destination = $destination_folder . str_shuffle(time() . rand(111111, 999999)) . "." . $ftype;
        if (file_exists($destination) && $overwrite != true) {
            $data['path'] = '';
            $data['code'] = 0;
            $data['message'] = '已存在同名文件！';
            echo json_encode($data);
            exit;
        }
        if (!move_uploaded_file($filename, $destination)) {
            $data['path'] = '';
            $data['code'] = 0;
            $data['message'] = '移动文件出错！';
            echo json_encode($data);
            exit;
        }
        $pinfo = pathinfo($destination);
        $fname = $pinfo['basename'];
        $data['path'] = $destination;
        $data['code'] = 1;
        $data['message'] = '上传成功！';
        echo json_encode($data);
        @require_once(IA_ROOT . '/framework/function/file.func.php');
        @$filename = $fname;
        @file_remote_upload($filename);
    }


    //获取轮播图

    public function doPageAd()
    {
        global $_GPC, $_W;
        //  $res=pdo_getall('zh_gjhdbm_ad',array('uniacid'=>$_W['uniacid'],'status'=>1,'type'=>$_GPC['type']));
        $where = " where uniacid=:uniacid and status=1 and type=:type ";
        $data[':uniacid'] = $_W['uniacid'];
        $data[':type'] = $_GPC['type'];
        if ($_GPC['cityname']) {
            $where .= " and (cityname LIKE  concat('%', :name,'%') or cityname='')";
            $data[':name'] = $_GPC['cityname'];
        }
        $sql = "select *  from " . tablename("zh_gjhdbm_ad") . $where . " order by id  desc ";
        $list = pdo_fetchall($sql, $data);
        echo json_encode($list);
    }



    //获取url

    // public function doPageUrl(){
    // 	global $_W;
    // 	//获取七牛设置
    // 	$qi=pdo_get('zh_gjhdbm_qiniu',array('uniacid'=>$_W['uniacid']));
    // 	if($qi['is_open']==1){
    // 		$url=$qi['url'].'/';
    // 	}else{
    // 		$url=$_W['siteroot'].'attachment/';
    // 	}
    // 	echo $url;
    // }

    public function doPageUrl()
    {
        global $_GPC, $_W;
        echo $_W['attachurl'];
    }


//导航列表
    public function doPageGetNav()
    {
        global $_GPC, $_W;
        $res = pdo_getall('zh_gjhdbm_nav', array('uniacid' => $_W['uniacid'], 'status' => 1), array(), '', 'orderby asc');
        echo json_encode($res);
    }


    //分类列表
    public function doPageTypeList()
    {
        global $_GPC, $_W;
        $res = pdo_getall('zh_gjhdbm_type', array('uniacid' => $_W['uniacid'], 'state' => 1), array(), '', 'num asc');
        echo json_encode($res);
    }


    //活动列表
    public function doPageActivityList()
    {
        global $_GPC, $_W;
        $pageindex = max(1, intval($_GPC['page']));
        $pagesize = 10;
        $data[':uniacid'] = $_W['uniacid'];
        $where = " where uniacid=:uniacid and status=2 and is_close=1  ";
        if ($_GPC['type_id']) {
            $where .= " and  type_id=:type_id ";
            $data[':type_id'] = $_GPC['type_id'];
        }
        if ($_GPC['cityname']) {
            $where .= " and (cityname LIKE  concat('%', :name,'%') or cityname='')";
            $data[':name'] = $_GPC['cityname'];
        }
        if ($_GPC['activity_type']) {
            $where .= " and  activity_type=:activity_type ";
            $data[':activity_type'] = $_GPC['activity_type'];
        }
        if ($_GPC['start_time']) {
            $time = strtotime($_GPC['start_time']);
            $end_time = strtotime($_GPC['start_time'] . "23:59:59");
            $where .= " and  start_time >= $time and  start_time < $end_time";
        }
        if ($_GPC['keywords']) {
            $where .= " and title LIKE  concat('%', :name,'%') ";
            $data[':name'] = $_GPC['keywords'];
        }
        $sql = "select *  from " . tablename("zh_gjhdbm_activity") . $where . " order by id	desc ";
        $select_sql = $sql . " LIMIT " . ($pageindex - 1) * $pagesize . "," . $pagesize;
        $list = pdo_fetchall($select_sql, $data);
        echo json_encode($list);
    }

    //活动详情
    public function doPageActivityDetails()
    {
        global $_GPC, $_W;
        pdo_update('zh_gjhdbm_activity', array('views +=' => 1), array('id' => $_GPC['activity_id']));
        $res = pdo_get('zh_gjhdbm_activity', array('id' => $_GPC['activity_id']));
        echo json_encode($res);
    }


    //城市列表
    public function doPageGetcity()
    {
        global $_GPC, $_W;
        $sql = "select *  from " . tablename("zh_gjhdbm_city") . " where uniacid=:uniacid order by time desc ";
        $list = pdo_fetchall($sql, array(':uniacid' => $_W['uniacid']));
        echo json_encode($list);
    }


    //获取系统设置
    public function doPageGetSystem()
    {
        global $_GPC, $_W;
        $res = pdo_get('zh_gjhdbm_system', array('uniacid' => $_W['uniacid']));
        echo json_encode($res);

    }


    //报名信息
    public function doPageGetBmInfo()
    {
        global $_GPC, $_W;
        $res = pdo_getall('zh_gjhdbm_enroll', array('uniacid' => $_W['uniacid'], 'status' => 1));
        echo json_encode($res);
    }


//保存活动
    public function doPageSaveActivity()
    {
        global $_GPC, $_W;
        $res = pdo_get('zh_gjhdbm_system', array('uniacid' => $_W['uniacid']));
        $data['user_id'] = $_GPC['user_id'];
        $data['title'] = $_GPC['title'];
        $data['sponsor'] = $_GPC['sponsor'];
        $data['link_tel'] = $_GPC['link_tel'];
        $data['logo'] = $_GPC['logo'];
        $data['hx_code'] = $_GPC['hx_code'];
        $data['start_time'] = strtotime($_GPC['start_time']);
        $data['end_time'] = strtotime($_GPC['end_time']);
        //$data['limit_num']=$_GPC['limit_num'];
        $data['activity_type'] = $_GPC['activity_type'];
        $data['join_type'] = $_GPC['join_type'];
        $data['content'] = html_entity_decode($_GPC['content']);
        $data['hd_imgs'] = $_GPC['hd_imgs'];
        $data['type_id'] = $_GPC['type_id'];
        $data['zd_money'] = $_GPC['zd_money'];
        if ($res['hdsh_open'] == 1) {
            $data['status'] = '1';
        }
        if ($res['hdsh_open'] == 2) {
            $data['status'] = '2';
            $data['sh_time'] = time();
        }
        $data['cityname'] = $_GPC['cityname'];
        $data['address'] = $_GPC['address'];
        $data['coordinates'] = $_GPC['coordinates'];
        //$data['cost']=$_GPC['cost'];
        $data['bm_check'] = $_GPC['bm_check'];
        $data['bm_info'] = $_GPC['bm_info'];
        $data['time'] = time();
        $data['uniacid'] = $_W['uniacid'];
        if ($_GPC['activity_id']) {
            $rst = pdo_update('zh_gjhdbm_activity', $data, array('id' => $_GPC['activity_id']));
            if ($rst) {
                echo '1';
            } else {
                echo '2';
            }

        } else {
            $res = pdo_insert('zh_gjhdbm_activity', $data);
            $activity_id = pdo_insertid();
            if ($res) {
                $a = json_decode(html_entity_decode($_GPC['ticket']));
                $sz = json_decode(json_encode($a), true);
                //二维数组
                foreach ($sz as $key => $value) {
                    $data2['activity_id'] = $activity_id;
                    $data2['tk_name'] = $value['tk_name'];
                    $data2['type'] = $value['type'];
                    $data2['money'] = $value['money'];
                    $data2['total_num'] = $value['total_num'];
                    $data2['limit_num'] = $value['limit_num'];
                    $data2['bm_check'] = $value['bm_check'];
                    $data2['uniacid'] = $_W['uniacid'];
                    $res = pdo_insert('zh_gjhdbm_ticket', $data2);
                }
                echo $activity_id;
            } else {
                echo '2';
            }
        }

    }


//保存关注
    public function doPageSaveFollow()
    {
        global $_W, $_GPC;
        $data['activity_id'] = $_GPC['activity_id'];
        $data['user_id'] = $_GPC['user_id'];
        $data['time'] = time();
        $data['uniacid'] = $_W['uniacid'];
        $res = pdo_insert('zh_gjhdbm_follow', $data);
        if ($res) {
            pdo_update('zh_gjhdbm_activity', array('gz_num +=' => 1), array('id' => $_GPC['activity_id']));
            echo '1';
        } else {
            echo '2';
        }
    }


//取消关注
    public function doPageCancelFollow()
    {
        global $_W, $_GPC;
        $res = pdo_delete('zh_gjhdbm_follow', array('user_id' => $_GPC['user_id'], 'activity_id' => $_GPC['activity_id']));
        if ($res) {
            echo '1';
        } else {
            echo '2';
        }
    }


//查找改用户留言次数
    public function doPageGetLyNum()
    {
        global $_W, $_GPC;
        $count = pdo_get('zh_gjhdbm_assess', array('uniacid' => $_W['uniacid'], 'user_id' => $_GPC['user_id']), array('count(id) as count'));
        echo $count['count'];
    }


//保存留言
    public function doPageSaveAssess()
    {
        global $_W, $_GPC;
        $data['activity_id'] = $_GPC['activity_id'];
        $data['user_id'] = $_GPC['user_id'];
        $data['content'] = $_GPC['content'];
        $data['status'] = 1;
        $data['cerated_time'] = date("Y-m-d H:i:s", time());
        $data['uniacid'] = $_W['uniacid'];
        $res = pdo_insert('zh_gjhdbm_assess', $data);
        if ($res) {
            echo '1';
        } else {
            echo '2';
        }
    }


//活动留言列表
    public function doPageActivityAssessList()
    {
        global $_GPC, $_W;
        $pageindex = max(1, intval($_GPC['page']));
        $pagesize = 10;
        $data[':uniacid'] = $_W['uniacid'];
        $data[':activity_id'] = $_GPC['activity_id'];
        $where = " where a.uniacid=:uniacid and a.activity_id=:activity_id ";
        $sql = "select a.*,b.name,b.img  from " . tablename("zh_gjhdbm_assess") . " a left join " . tablename('zh_gjhdbm_user') . " b on a.user_id=b.id" . $where . " order by a.id desc ";
        $select_sql = $sql . " LIMIT " . ($pageindex - 1) * $pagesize . "," . $pagesize;
        $list = pdo_fetchall($select_sql, $data);
        echo json_encode($list);

    }


//我要参加(获取票卷信息)
    public function doPageGetTicket()
    {
        global $_W, $_GPC;
        $res = pdo_getall('zh_gjhdbm_ticket', array('activity_id' => $_GPC['activity_id']));
        echo json_encode($res);
    }


//下一步
    public function doPageGethdbm()
    {
        global $_W, $_GPC;
        $res = pdo_get('zh_gjhdbm_activity', array('id' => $_GPC['activity_id']), 'bm_info');
        $arr = explode(",", $res['bm_info']);
        $list = pdo_getall('zh_gjhdbm_enroll', array('id' => $arr), 'name');
        echo json_encode($list);
    }


    //保存报名信息
    public function doPageSaveBm()
    {
        global $_W, $_GPC;
        function sjs()
        {
            $a = range(0, 9);
            for ($i = 0; $i < 12; $i++) {
                $b[] = array_rand($a);
            }
            return join("", $b);
        }

        $rand = rand(1111, 9999);
        $order_num = date('YmdHis', time()) . $rand;
        $res = pdo_get('zh_gjhdbm_activity', array('id' => $_GPC['activity_id']));
        //接收购票信息
        $a = json_decode(html_entity_decode($_GPC['ticket']));
        $sz = json_decode(json_encode($a), true);
        foreach ($sz as $key => $value) {
            $data['order_num'] = $order_num;
            for ($i = 0; $i < $value['gm_num']; $i++) {
                $data['user_id'] = $_GPC['user_id'];
                $data['activity_id'] = $_GPC['activity_id'];
                $data['hd_title'] = $res['title'];
                $data['start_time'] = $res['start_time'];
                $data['end_time'] = $res['end_time'];
                $data['hx_code'] = $res['hx_code'];
                $data['hd_place'] = $res['activity_type'];
                $data['tk_name'] = $value['tk_name'];
                $data['ticket_id'] = $value['ticket_id'];
                $data['code'] = sjs();
                if ($value['bm_check'] == 1) {
                    $data['state'] = 1;
                }
                if ($value['bm_check'] == 2) {
                    $data['state'] = 2;
                }
                $data['money'] = $value['money'];
                if ($value['money'] > 0) {
                    $data['status'] = 0;
                } else {
                    $data['status'] = 1;
                }
                $data['time'] = time();
                $data['uniacid'] = $_W['uniacid'];
                $res2 = pdo_insert('zh_gjhdbm_bmlist', $data);
                $bm_id = pdo_insertid();
            }
            if ($value['money'] == "0.00") {
                //修改余票信息
                pdo_update('zh_gjhdbm_ticket', array('yg_num +=' => $value['gm_num']), array('id' => $value['ticket_id']));
            }
        }

//保存报名信息
        $bm = json_decode(html_entity_decode($_GPC['bm']));
        $bminfo = json_decode(json_encode($bm), true);
        foreach ($bminfo as $key => $value) {
            $data2['order_num'] = $order_num;
            $data2['activity_id'] = $_GPC['activity_id'];
            $data2['user_id'] = $_GPC['user_id'];
            $data2['name'] = $value['name'];
            $data2['value'] = $value['value'];
            $data2['uniacid'] = $_W['uniacid'];
            $rst = pdo_insert('zh_gjhdbm_bmextend', $data2);
        }
        //$bm_id=pdo_insertid();
        if ($res2) {
            echo $bm_id;
        } else {
            echo '下单失败';
        }
    }


    //微信支付
    public function doPagePay()
    {
        global $_W, $_GPC;
        include IA_ROOT . '/addons/zh_gjhdbm/wxpay.php';
        $res = pdo_get('zh_gjhdbm_system', array('uniacid' => $_W['uniacid']));
        //查找订单编号
        $rst = pdo_get('zh_gjhdbm_bmlist', array('id' => $_GPC['bm_id']), 'order_num');
        $appid = $res['appid'];
        $openid = $_GPC['openid'];//oQKgL0ZKHwzAY-KhiyEEAsakW5Zg
        $mch_id = $res['mchid'];
        $key = $res['wxkey'];
        $out_trade_no = $mch_id . time();
        $root = $_W['siteroot'];
        pdo_update('zh_gjhdbm_bmlist', array('sh_ordernum' => $out_trade_no), array('order_num' => $rst['order_num']));
        $total_fee = $_GPC['money'];
        if (empty($total_fee)) //押金
        {
            $body = "订单付款";
            $total_fee = floatval(99 * 100);
        } else {
            $body = "订单付款";
            $total_fee = floatval($total_fee * 100);
        }
        $weixinpay = new WeixinPay($appid, $openid, $mch_id, $key, $out_trade_no, $body, $total_fee, $root);
        $return = $weixinpay->pay();
        echo json_encode($return);
    }


//查看活动报名人数
    public function doPageBmList()
    {
        global $_GPC, $_W;
        $sql = " select c.name,c.img,xx.time  from (select  user_id, activity_id ,time from " . tablename('zh_gjhdbm_bmlist') . " where activity_id=:activity_id group by user_id) xx  " . " left join " . tablename("zh_gjhdbm_user") . " c on xx.user_id=c.id";
        $list = pdo_fetchall($sql, array(':activity_id' => $_GPC['activity_id']));
        echo json_encode($list);
    }


//票卷统计

    public function doPageTicketCount()
    {
        global $_GPC, $_W;
        $user_id = $_GPC['user_id'];
        $sql = "select count(case when state=1 then 1 end) as 'shz', count(case when state=2 then 1 end) as 'dcj', count(case when state=3 then 1 end) as 'yyp',
	count(case when state=5 then 1 end) as 'ytp' from" . tablename("zh_gjhdbm_bmlist") . " where user_id=:user_id  and status=1 ";
        $list = pdo_fetchall($sql, array(':user_id' => $user_id));
        echo json_encode($list);
    }


//我的票卷

    public function doPageMyTickets()
    {
        global $_GPC, $_W;
        $pageindex = max(1, intval($_GPC['page']));
        $pagesize = 10;
        $where = " where a.user_id=:user_id and a.status=1";
        $data[':user_id'] = $_GPC['user_id'];
        if ($_GPC['state']) {
            $where .= " and a.state=:state";
            $data[':state'] = $_GPC['state'];
        }
        $sql = " select a.*,c.user_id as fu_id from " . tablename('zh_gjhdbm_bmlist') . " a " . " left join " . tablename("zh_gjhdbm_activity") . " c on a.activity_id=c.id" . $where . " order by id desc ";
        $select_sql = $sql . " LIMIT " . ($pageindex - 1) * $pagesize . "," . $pagesize;
        $list = pdo_fetchall($select_sql, $data);
        echo json_encode($list);
    }


//票卷详情

    public function doPagePjDetails()
    {
        global $_GPC, $_W;
        $sql = " select a.*,c.user_id as fu_id  from  " . tablename('zh_gjhdbm_bmlist') . " a " . " left join " . tablename("zh_gjhdbm_activity") . " c on a.activity_id=c.id where a.id=:ticket_id ";
        $res = pdo_fetch($sql, array(':ticket_id' => $_GPC['ticket_id']));
        $sql2 = " select name ,value from" . tablename('zh_gjhdbm_bmextend') . " where order_num=(select order_num from " . tablename('zh_gjhdbm_bmlist') . " where id=:ticket_id)";
        $res2 = pdo_fetchall($sql2, array(':ticket_id' => $_GPC['ticket_id']));
        $list['pjdetails'] = $res;
        $list['bminfo'] = $res2;
        echo json_encode($list);
    }


//票卷的二维码
    public function doPagePjCode()
    {
        global $_W, $_GPC;
        load()->func('tpl');
        function getCoade($ticket_id, $fu_id)
        {
            function getaccess_token()
            {
                global $_W, $_GPC;
                $res = pdo_get('zh_gjhdbm_system', array('uniacid' => $_W['uniacid']));
                $appid = $res['appid'];
                $secret = $res['appsecret'];
                // $appid="wx6c0ba0fee625061e";
                // $secret="6df0683a28742c52a0f845901a5385c1";
                $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret . "";
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                $data = curl_exec($ch);
                curl_close($ch);
                $data = json_decode($data, true);
                return $data['access_token'];
            }

            function set_msg($ticket_id, $fu_id)
            {
                $access_token = getaccess_token();
                $data2 = array(
                    "scene" => $ticket_id . "," . $fu_id,
                    "page" => "zh_gjhdbm/pages/logs/inspect_ticket",
                    "width" => 100
                );
                $data2 = json_encode($data2);
                //$url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".$access_token."";
                $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" . $access_token . "";
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $data2);
                $data = curl_exec($ch);
                curl_close($ch);
                return $data;
            }

            $img = set_msg($ticket_id, $fu_id);
            $img = base64_encode($img);
            return $img;
        }

        echo getCoade($_GPC['ticket_id'], $_GPC['fu_id']);
    }


//我关注的活动
    public function doPageMyFollow()
    {
        global $_GPC, $_W;
        $sql = " select b.* from " . tablename('zh_gjhdbm_follow') . "a left join" . tablename('zh_gjhdbm_activity') . " b on a.activity_id=b.id where a.user_id=:user_id order by a.id desc";
        $res = pdo_fetchall($sql, array(':user_id' => $_GPC['user_id']));
        echo json_encode($res);
    }



//以下 我的接口
//主办方
//我的活动
    public function doPageMyActivity()
    {
        global $_GPC, $_W;
        $pageindex = max(1, intval($_GPC['page']));
        $pagesize = 10;
        $data[':uniacid'] = $_W['uniacid'];
        $data[':user_id'] = $_GPC['user_id'];
        $where = " where uniacid=:uniacid and user_id=:user_id ";
        $sql = "select *  from " . tablename("zh_gjhdbm_activity") . $where . " order by id	desc ";
        $select_sql = $sql . " LIMIT " . ($pageindex - 1) * $pagesize . "," . $pagesize;
        $list = pdo_fetchall($select_sql, $data);
        foreach ($list as $key => $value) {
            $sql = " select sum(money) as total_money, count(*) as total_ticket from" . tablename('zh_gjhdbm_bmlist') . "where activity_id=:id and status=1 and state!=5";
            $res = pdo_fetch($sql, array(':id' => $value['id']));
            //$list[$key]['total_money']=$res['total_money'];
            $list[$key]['total_ticket'] = $res['total_ticket'];
        }
        echo json_encode($list);
    }


//留言管理
    public function doPageMyAssess()
    {
        global $_GPC, $_W;
        $sql = " select a.*,b.name,b.img from (select * from " . tablename('zh_gjhdbm_assess') . " where activity_id in (select id from" . tablename('zh_gjhdbm_activity') . " where uniacid=:uniacid and user_id=:user_id and status=2 ) ) a left join " . tablename('zh_gjhdbm_user') . " b on a.user_id=b.id order by a.id desc";
        $res = pdo_fetchall($sql, array(':uniacid' => $_W['uniacid'], ':user_id' => $_GPC['user_id']));
        //var_dump($res);die;
        echo json_encode($res);
    }


//回复留言
    public function doPageSaveReply()
    {
        global $_W, $_GPC;
        $data['reply'] = $_GPC['reply'];
        $data['status'] = 2;
        $data['reply_time'] = date("Y-m-d H:i:s", time());
        $res = pdo_update('zh_gjhdbm_assess', $data, array('id' => $_GPC['assess_id']));
        if ($res) {
            echo '1';
        } else {
            echo '2';
        }

    }

//删除留言
    public function doPageDelAssess()
    {
        global $_W, $_GPC;
        $res = pdo_delete('zh_gjhdbm_assess', array('id' => $_GPC['assess_id']));
        if ($res) {
            echo '1';
        } else {
            echo '2';
        }
    }

//我的收入
    public function doPageMyIncome()
    {
        global $_GPC, $_W;
        $sql = " select sum(money) as money from" . tablename('zh_gjhdbm_bmlist') . " where activity_id in (select id from " . tablename("zh_gjhdbm_activity") . "where uniacid=:uniacid and user_id=:user_id )";
        $res = pdo_fetch($sql, array(':uniacid' => $_W['uniacid'], ':user_id' => $_GPC['user_id']));
        echo json_encode($res);
    }


//关闭/开启活动报名
    public function doPageCloseActivity()
    {
        global $_GPC, $_W;
        $res = pdo_update('zh_gjhdbm_activity', array('is_close' => $_GPC['is_close']), array('id' => $_GPC['activity_id']));
        if ($res) {
            echo '1';
        } else {
            echo '2';
        }
    }


//票卷审核
    public function doPagePjCheck()
    {
        global $_GPC, $_W;
        $where = " where  status=1 ";
        $state = empty($_GPC['state']) ? 1 : $_GPC['state'];
        if ($state) {
            $where .= " and state=:state";
            $data[':state'] = $state;
        }
        $data[':user_id'] = $_GPC['user_id'];
        $sql = " select xx.*,b.name,b.img from (select * from" . tablename('zh_gjhdbm_bmlist') . "where activity_id in ( select id from" . tablename('zh_gjhdbm_activity') . " where user_id=:user_id)) xx left join  " . tablename('zh_gjhdbm_user') . "b on xx.user_id=b.id" . $where . " order by xx.id desc";
        $res = pdo_fetchall($sql, $data);
        echo json_encode($res);
    }


//审核票卷(通过/拒绝)通过2，拒绝6
    public function doPageUpdPj()
    {
        global $_GPC, $_W;
        $res = pdo_update('zh_gjhdbm_bmlist', array('state' => $_GPC['state']), array('id' => $_GPC['ticket_id']));
        if ($res) {
            echo '1';
        } else {
            echo '2';
        }
    }



//退票审核


////////////////////////////////////////////

//主办方管理
    public function doPageSaveSponsor()
    {
        global $_GPC, $_W;
        $data['user_id'] = $_GPC['user_id'];
        $data['name'] = $_GPC['name'];
        $data['logo'] = $_GPC['logo'];
        $data['tel'] = $_GPC['tel'];
        $data['details'] = base64_encode($_GPC['details']);
        $data['time'] = time();
        $data['uniacid'] = $_W['uniacid'];
        if ($_GPC['id'] == '') {
            $res = pdo_insert('zh_gjhdbm_sponsor', $data);
        } else {
            $res = pdo_update('zh_gjhdbm_sponsor', $data, array('id' => $_GPC['id']));
        }
        if ($res) {
            echo '1';
        } else {
            echo '2';
        }
    }


//获取主办方资料
    public function doPageGetSponsor()
    {
        global $_GPC, $_W;
        $res = pdo_get('zh_gjhdbm_sponsor', array('user_id' => $_GPC['user_id']));
        if ($res) {
            $res['details'] = base64_decode($res['details']);
        }
        echo json_encode($res);
    }


//保存认证信息
    public function doPageSaveAttestation()
    {
        global $_GPC, $_W;
        $data['user_id'] = $_GPC['user_id'];
        $data['name'] = $_GPC['name'];
        $data['zj_name'] = $_GPC['zj_name'];
        $data['code'] = $_GPC['code'];
        $data['zm_img'] = $_GPC['zm_img'];
        $data['bm_img'] = $_GPC['bm_img'];
        $data['type'] = $_GPC['type'];
        $data['rz_time'] = time();
        $data['state'] = 1;
        $data['uniacid'] = $_W['uniacid'];
        $rst = pdo_get('zh_gjhdbm_attestation', array('user_id' => $_GPC['user_id'], 'state' => 3));
        if ($rst) {
            $res = pdo_update('zh_gjhdbm_attestation', $data, array('user_id' => $_GPC['user_id']));
        } else {
            $res = pdo_insert('zh_gjhdbm_attestation', $data);
            $rz_id = pdo_insertid();
        }
        if ($res) {
            echo $rz_id;
        } else {
            echo 'error';
        }

    }


//获取用户信息
    public function doPageGetUserInfo()
    {
        global $_GPC, $_W;
        //$res=pdo_get('zh_gjhdbm_user',array('id'=>$_GPC['user_id']));
        //echo json_encode($res);
        $sql = " select a.*,b.state as sh from" . tablename('zh_gjhdbm_user') . " a left join" . tablename('zh_gjhdbm_attestation') . " b on a.id=b.user_id where a.id=:id";
        $res = pdo_fetch($sql, array(':id' => $_GPC['user_id']));
        echo json_encode($res);
    }


//该用户是否关注活动
    public function doPageCheckGz()
    {
        global $_GPC, $_W;
        $res = pdo_get('zh_gjhdbm_follow', array('user_id' => $_GPC['user_id'], 'activity_id' => $_GPC['activity_id']));
        if ($res) {
            echo '1';//已关注
        } else {
            echo '2';//未关注
        }
    }



//以下核销管理

//添加核销人员二维码生成
    public function doPageHxCode()
    {
        global $_W, $_GPC;
        load()->func('tpl');
        function getCoade($user_id)
        {
            function getaccess_token()
            {
                global $_W, $_GPC;
                $res = pdo_get('zh_gjhdbm_system', array('uniacid' => $_W['uniacid']));
                $appid = $res['appid'];
                $secret = $res['appsecret'];
                // $appid='wx6c0ba0fee625061e';
                // $secret='6df0683a28742c52a0f845901a5385c1';
                $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret . "";
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                $data = curl_exec($ch);
                curl_close($ch);
                $data = json_decode($data, true);
                return $data['access_token'];
            }

            function set_msg($user_id)
            {
                $access_token = getaccess_token();
                $data2 = array(
                    "scene" => $user_id,
                    "page" => "zh_gjhdbm/pages/piaoquaninfo/add_mark",
                    "width" => 100
                );
                $data2 = json_encode($data2);
                //$url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".$access_token."";
                $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" . $access_token . "";
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $data2);
                $data = curl_exec($ch);
                curl_close($ch);
                return $data;
            }

            $img = set_msg($user_id);
            $img = base64_encode($img);
            return $img;
        }

        echo getCoade($_GPC['user_id']);
    }


    //添加核销员
    public function doPageAddVerification()
    {
        global $_W, $_GPC;
        $rst = pdo_get('zh_gjhdbm_hx', array('user_id' => $_GPC['user_id'], 'hx_id' => $_GPC['hx_id']));
        if (!$rst) {
            $data['user_id'] = $_GPC['user_id'];
            $data['hx_id'] = $_GPC['hx_id'];
            $data['time'] = time();
            $data['uniacid'] = $_W['uniacid'];
            $res = pdo_insert('zh_gjhdbm_hx', $data);
            if ($res) {
                echo '1';
            } else {
                echo '2';
            }
        } else {
            echo '重复添加核销员';
        }
    }


    //删除核销员

    public function doPageDelVerification()
    {
        global $_W, $_GPC;
        $res = pdo_delete('zh_gjhdbm_hx', array('id' => $_GPC['id']));
        if ($res) {
            echo '1';
        } else {
            echo '2';
        }
    }


//核销员列表
    public function doPageHxList()
    {
        global $_W, $_GPC;
        $sql = "select b.name,b.img,a.id  from " . tablename("zh_gjhdbm_hx") . " a" . " left join " . tablename("zh_gjhdbm_user") . " b on b.id=a.hx_id  WHERE a.user_id=:user_id ";
        $res = pdo_fetchall($sql, array(':user_id' => $_GPC['user_id']));
        echo json_encode($res);
    }


//核销票卷(验票)
    public function doPageIsHx()
    {
        global $_W, $_GPC;
        //$sql=" select user_id from ".tablename('zh_gjhdbm_activity')." where id=( select activity_id from)".tablename('zh_gjhdbm_bmlist')." where id=:id ";
        $sql = " select b.user_id,a.money,a.user_id as uid from " . tablename('zh_gjhdbm_bmlist') . " a left join" . tablename('zh_gjhdbm_activity') . " b on a.activity_id=b.id where a.id=:id";
        $rst = pdo_fetch($sql, array(':id' => $_GPC['ticket_id']));
        $res = pdo_get('zh_gjhdbm_hx', array('user_id' => $rst['user_id'], 'hx_id' => $_GPC['user_id']));
        if ($res || $rst['user_id'] == $_GPC['user_id']) {
            $rst2 = pdo_update('zh_gjhdbm_bmlist', array('state' => 3), array('id' => $_GPC['ticket_id']));
            //增加活动发布者金额
            if ($rst['money'] > 0) {
                pdo_update('zh_gjhdbm_user', array('money +=' => $rst['money']), array('id' => $rst['user_id']));
            }
            //佣金计算
            $set = pdo_get('zh_gjhdbm_fxset', array('uniacid' => $_W['uniacid']));
            if ($set['is_open'] == 1) {//开启分销
                $user = pdo_get('zh_gjhdbm_fxuser', array('fx_user' => $rst['uid']));
                if ($user) {
                    $userid = $user['user_id'];//上线id
                    $money = $rst['money'] * ($set['commission'] / 100);//一级佣金
                    $data1['user_id'] = $userid;//上线id
                    $data1['son_id'] = $rst['uid'];//下线id
                    $data1['money'] = $money;//金额
                    $data1['time'] = time();//时间
                    $data1['order_id'] = $_GPC['ticket_id'];
                    $data1['note'] = '一级佣金';
                    $data1['state'] = 2;
                    $data1['uniacid'] = $_W['uniacid'];
                    pdo_insert('zh_gjhdbm_earnings', $data1);
                }
                if ($set['is_ej'] == 1) {//开启二级分销
                    $user2 = pdo_get('zh_gjhdbm_fxuser', array('fx_user' => $user['user_id']));//上线的上线
                    if ($user2) {
                        $userid2 = $user2['user_id'];//上线的上线id
                        $money = $rst['money'] * ($set['commission2'] / 100);//二级佣金
                        $data3['user_id'] = $userid2;//上线id
                        $data3['son_id'] = $rst['uid'];//下线id
                        $data3['money'] = $money;//金额
                        $data3['time'] = time();//时间
                        $data3['order_id'] = $_GPC['ticket_id'];
                        $data3['note'] = '二级佣金';
                        $data3['state'] = 2;
                        $data3['uniacid'] = $_W['uniacid'];
                        pdo_insert('zh_gjhdbm_earnings', $data3);
                    }
                }
            }

            if ($rst2) {
                echo 1;
            } else {
                echo 2;
            }
        } else {
            echo '无核销权限';
        }
    }


//待结算的钱
    public function doPageDjsmoney()
    {
        global $_W, $_GPC;
        $sql = " select sum(money) as djsmoney from " . tablename('zh_gjhdbm_bmlist') . " where activity_id in ( select id from " . tablename('zh_gjhdbm_activity') . " where user_id=:user_id) and status=1 and state !=3 and state !=5 and state !=6";
        $res = pdo_fetch($sql, array(':user_id' => $_GPC['user_id']));
        echo json_encode($res);
    }


//保存提现申请
    public function doPageSaveTx()
    {
        global $_W, $_GPC;
        $data['user_id'] = $_GPC['user_id'];
        $data['name'] = $_GPC['name'];
        $data['account'] = $_GPC['account'];
        $data['tx_cost'] = $_GPC['tx_cost'];
        $data['sj_cost'] = $_GPC['sj_cost'];
        $data['state'] = 1;
        $data['time'] = time();
        $data['is_delete'] = 1;
        $data['uniacid'] = $_W['uniacid'];
        $res = pdo_insert('zh_gjhdbm_withdrawal', $data);
        if ($res) {
            pdo_update('zh_gjhdbm_user', array('money -=' => $_GPC['tx_cost']), array('id' => $_GPC['user_id']));
            echo '1';
        } else {
            echo '2';
        }
    }


//活动的票卷
    public function doPageHdPjlist()
    {
        global $_GPC, $_W;
        $pageindex = max(1, intval($_GPC['page']));
        $pagesize = 10;
        $data[':uniacid'] = $_W['uniacid'];
        $data[':activity_id'] = $_GPC['activity_id'];
        $where = " where uniacid=:uniacid and activity_id=:activity_id ";
        if ($_GPC['state']) {
            $where .= " and state=:state";
            $data[':state'] = $_GPC['state'];
        }
        $sql = "select *  from " . tablename("zh_gjhdbm_bmlist") . $where . " order by id	desc ";
        $select_sql = $sql . " LIMIT " . ($pageindex - 1) * $pagesize . "," . $pagesize;
        $list = pdo_fetchall($select_sql, $data);
        echo json_encode($list);
    }


//活动的收入
    public function doPageHdsr()
    {
        global $_W, $_GPC;
        $sql = " select sum(money) as total_money from" . tablename('zh_gjhdbm_bmlist') . " where activity_id=:activity_id and status=1 and state< 5 and money>0";
        $res = pdo_fetch($sql, array(':activity_id' => $_GPC['activity_id']));
        $sql2 = " select sum(money) as js_money from" . tablename('zh_gjhdbm_bmlist') . " where activity_id=:activity_id and status=1 and state=3 and money>0";
        $res2 = pdo_fetch($sql2, array(':activity_id' => $_GPC['activity_id']));
        $sql3 = " select sum(money) as djs_money from" . tablename('zh_gjhdbm_bmlist') . " where activity_id=:activity_id and status=1 and (state=1 or state=2 or state=4) and money>0";
        $res3 = pdo_fetch($sql3, array(':activity_id' => $_GPC['activity_id']));
        $money = array_merge($res, $res2, $res3);
        echo json_encode($money);
    }


//活动未结算列表
    public function doPageHdUnsettled()
    {
        global $_W, $_GPC;
        $sql3 = " select * from" . tablename('zh_gjhdbm_bmlist') . " where activity_id=:activity_id and status=1 and (state=1 or state=2 or state=4) and money>0";
        $res3 = pdo_fetchall($sql3, array(':activity_id' => $_GPC['activity_id']));
        echo json_encode($res3);
    }


//主办方查看
    public function doPageGetSponsorInfo()
    {
        global $_W, $_GPC;
        $res = pdo_get('zh_gjhdbm_sponsor', array('name' => $_GPC['name']));
        if ($res) {
            $res['details'] = base64_decode($res['details']);
        }
        echo json_encode($res);
    }


//申请退款
    public function doPageApplyRefund()
    {
        global $_W, $_GPC;
        $res = pdo_update('zh_gjhdbm_bmlist', array('state' => $_GPC['state']), array('id' => $_GPC['ticket_id']));
        if ($res) {
            echo '1';
        } else {
            echo '2';
        }
    }


//退票
    public function doPageRefund()
    {
        global $_W, $_GPC;
        include_once IA_ROOT . '/addons/zh_gjhdbm/cert/WxPay.Api.php';
        load()->model('account');
        load()->func('communication');
        $refund_order = pdo_get('zh_gjhdbm_bmlist', array('id' => $_GPC['ticket_id']));
        $total = pdo_get('zh_gjhdbm_bmlist', array('sh_ordernum' => $refund_order['sh_ordernum']), array('sum(money) as money'));
        $WxPayApi = new WxPayApi();
        $input = new WxPayRefund();
        $path_cert = IA_ROOT . "/addons/zh_gjhdbm/cert/" . 'apiclient_cert_' . $_W['uniacid'] . '.pem';
        $path_key = IA_ROOT . "/addons/zh_gjhdbm/cert/" . 'apiclient_key_' . $_W['uniacid'] . '.pem';
        $account_info = $_W['account'];
        $res = pdo_get('zh_gjhdbm_system', array('uniacid' => $_W['uniacid']));
        $appid = $res['appid'];
        $key = $res['wxkey'];
        $mchid = $res['mchid'];
        $out_trade_no = $refund_order['sh_ordernum'];
        $total_fee = $total['money'] * 100;
        $fee = $refund_order['money'] * 100;
        /*$out_trade_no=$refund_order['sh_ordernum'];
		$fee = $refund_order['money'] * 100;*/
        $input->SetAppid($appid);
        $input->SetMch_id($mchid);
        $input->SetOp_user_id($mchid);
        $input->SetRefund_fee($fee);
        $input->SetTotal_fee($total_fee);
        // $input->SetTransaction_id($refundid);
        $input->SetOut_refund_no($refund_order['code']);
        $input->SetOut_trade_no($out_trade_no);
        //var_dump($input);die;
        $result = $WxPayApi->refund($input, 6, $path_cert, $path_key, $key);
        if ($result['result_code'] == 'SUCCESS') {//退款成功
            //更改订单操作
            pdo_update('zh_gjhdbm_bmlist', array('state' => $_GPC['state']), array('id' => $_GPC['ticket_id']));
            echo '1';
        } else {
            echo '2';
        }

    }


//报名成功模板消息
    public function doPageMessage1()
    {
        global $_W, $_GPC;
        function getaccess_token($_W)
        {
            $res = pdo_get('zh_gjhdbm_system', array('uniacid' => $_W['uniacid']));
            $appid = $res['appid'];
            $secret = $res['appsecret'];
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret . "";
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            $data = curl_exec($ch);
            curl_close($ch);
            $data = json_decode($data, true);
            return $data['access_token'];
        }

        //设置与发送模板信息
        function set_msg($_W)
        {
            $access_token = getaccess_token($_W);
            $res = pdo_get('zh_gjhdbm_system', array('uniacid' => $_W['uniacid']));
            $sql = "select b.* from " . tablename("zh_gjhdbm_bmlist") . " a" . " left join " . tablename("zh_gjhdbm_activity") . " b on a.activity_id=b.id   WHERE a.id=:bm_id  ";
            $list = pdo_fetch($sql, array(':bm_id' => $_GET['bm_id']));
            $str = $list['activity_type'] == 1 ? '线上活动' : '线下活动';
            $time = date('Y-m-d H:i', $list['start_time']) . "~" . date('Y-m-d H:i', $list['end_time']);
            //下面是要填充模板的信息
            $formwork = '{
    			"touser": "' . $_GET["openid"] . '",
    			"template_id": "' . $res["tid1"] . '",
    			"form_id":"' . $_GET['form_id'] . '",
    			"data": {
    				"keyword1": {
    					"value": "' . $list['title'] . '",
    					"color": "#173177"
    				},
    				"keyword2": {
    					"value": "' . $str . '",
    					"color": "#173177"
    				},
    				"keyword3": {
    					"value": "' . $time . '",
    					"color": "#173177"
    				},
    				"keyword4": {
    					"value":  "' . $list['sponsor'] . '",
    					"color": "#173177"
    				},
    				"keyword5": {
    					"value": "' . $list['link_tel'] . '",
    					"color": "#173177"
    				}
    			}
    		}';
            $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" . $access_token . "";
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $formwork);
            $data = curl_exec($ch);
            curl_close($ch);
            return $data;

        }

        echo set_msg($_W);
    }

    function getaccess_token($_W)
    {
        $res = pdo_get('zh_gjhdbm_system', array('uniacid' => $_W['uniacid']));
        $appid = $res['appid'];
        $secret = $res['appsecret'];
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret . "";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $data = curl_exec($ch);
        curl_close($ch);
        $data = json_decode($data, true);
        return $data['access_token'];
    }

    /**
     * 案件消息推送
     */
    public function doPageMessage2()
    {
        global $_W, $_GPC;
        $case_id = $_GPC['case_id'];
        $form_id = $_GPC['form_id'];
        $userInfo = pdo_fetch("select c.*,u.*,d.* from " . tablename('zh_gjhdbm_case') . " as c left join " . tablename('zh_gjhdbm_deal') . " as d on c.deal_id = d.deal_id left join " . tablename('zh_gjhdbm_user') . " as u on c.apply_id = u.user_id where c.case_id = " . $case_id);
        if ($userInfo) {
            $status_txt = '';
            if ($userInfo['status'] == 1) {
                $status_txt = '已立案';
            } elseif ($userInfo['status'] == 2) {
                $status_txt = '已结案';
            }
            $access_token = getaccess_token($_W);
            $res = pdo_get('zh_gjhdbm_system', array('uniacid' => $_W['uniacid']));
            $formwork = '{
    			"touser": "' . $userInfo['openid'] . '",
    			"template_id": "' . $res["tid2"] . '",
    			"form_id":"' . $form_id . '",
    			"data": {
    				"keyword1": {
    					"value": "业务受理通知",
    					"color": "#173177"
    				},
    				"keyword2": {
    					"value": "' . $userInfo['name'] . '",
    					"color": "#173177"
    				},
    				"keyword3": {
    					"value": "' . $userInfo['event_num'] . '",
    					"color": "#173177"
    				},
    				"keyword4": {
    					"value":  "' . $status_txt . '",
    					"color": "#173177"
    				},
    				"keyword5": {
    					"value": "' . $userInfo['deal_name'] . '",
    					"color": "#173177"
    				}
    				"keyword6": {
    					"value": "' . $userInfo['deal_tel'] . '",
    					"color": "#173177"
    				}
    			}
    		}';
            $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" . $access_token . "";
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $formwork);
            $data = curl_exec($ch);
            curl_close($ch);
            return $data;
        }

    }


//短信验证码
    public function doPageSms2()
    {
        global $_W, $_GPC;
        $res = pdo_get('zh_gjhdbm_system', array('uniacid' => $_W['uniacid']));
        $tpl_id = $res['tpl_id'];
        $tel = $_GPC['tel'];
        $code = $_GPC['code'];
        $key = $res['appkey'];
        $url = "http://v.juhe.cn/sms/send?mobile=" . $tel . "&tpl_id=" . $tpl_id . "&tpl_value=%23code%23%3D" . $code . "&key=" . $key;
        $data = file_get_contents($url);
        print_r($data);
    }


//自定义底部菜单
    public function doPageDbMenu()
    {
        global $_W, $_GPC;
        $res = pdo_getall('zh_gjhdbm_menu', array('uniacid' => $_W['uniacid']), array(), '', 'sort ASC');
        echo json_encode($res);
    }


//解密
    public function doPageJiemi()
    {
        global $_W, $_GPC;
        $res = pdo_get('zh_gjhdbm_system', array('uniacid' => $_W['uniacid']));
        include_once IA_ROOT . "/addons/zh_gjhdbm/wxBizDataCrypt.php";
        $appid = $res['appid'];
        $sessionKey = $_GPC['sessionKey'];
        $encryptedData = $_GPC['data'];
        $iv = $_GPC['iv'];
        $pc = new WXBizDataCrypt($appid, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data);
        if ($errCode == 0) {
            //echo json_encode($data);
            print($data . "\n");
        } else {
            print($errCode . "\n");
        }
    }


//手动核销票卷
    public function doPageManualHx()
    {
        global $_W, $_GPC;
        $res = pdo_get('zh_gjhdbm_bmlist', array('id' => $_GPC['ticket_id'], 'hx_code' => $_GPC['hx_code']));
        if ($res) {
            pdo_update('zh_gjhdbm_bmlist', array('state' => 3), array('id' => $_GPC['ticket_id']));
            //佣金计算
            $set = pdo_get('zh_gjhdbm_fxset', array('uniacid' => $_W['uniacid']));
            if ($set['is_open'] == 1) {//开启分销
                $user = pdo_get('zh_gjhdbm_fxuser', array('fx_user' => $res['user_id']));
                if ($user) {
                    $userid = $user['user_id'];//上线id
                    $money = $res['money'] * ($set['commission'] / 100);//一级佣金
                    $data1['user_id'] = $userid;//上线id
                    $data1['son_id'] = $res['user_id'];//下线id
                    $data1['money'] = $money;//金额
                    $data1['time'] = time();//时间
                    $data1['order_id'] = $_GPC['ticket_id'];
                    $data1['note'] = '一级佣金';
                    $data1['state'] = 2;
                    $data1['uniacid'] = $_W['uniacid'];
                    pdo_insert('zh_gjhdbm_earnings', $data1);
                }
                if ($set['is_ej'] == 1) {//开启二级分销
                    $user2 = pdo_get('zh_gjhdbm_fxuser', array('fx_user' => $user['user_id']));//上线的上线
                    if ($user2) {
                        $userid2 = $user2['user_id'];//上线的上线id
                        $money = $res['money'] * ($set['commission2'] / 100);//二级佣金
                        $data3['user_id'] = $userid2;//上线id
                        $data3['son_id'] = $res['user_id'];//下线id
                        $data3['money'] = $money;//金额
                        $data3['time'] = time();//时间
                        $data3['order_id'] = $_GPC['ticket_id'];
                        $data3['note'] = '二级佣金';
                        $data3['state'] = 2;
                        $data3['uniacid'] = $_W['uniacid'];
                        pdo_insert('zh_gjhdbm_earnings', $data3);
                    }
                }
            }
            echo '1';
        } else {
            echo '2';
        }
    }


//认证模板消息
    public function doPageMessage3()
    {
        global $_W, $_GPC;
        function getaccess_token($_W)
        {
            $res = pdo_get('zh_gjhdbm_system', array('uniacid' => $_W['uniacid']));
            $appid = $res['appid'];
            $secret = $res['appsecret'];
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret . "";
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            $data = curl_exec($ch);
            curl_close($ch);
            $data = json_decode($data, true);
            return $data['access_token'];

        }

        //设置与发送模板信息
        function set_msg($_W)
        {
            $access_token = getaccess_token($_W);
            $res = pdo_get('zh_gjhdbm_system', array('uniacid' => $_W['uniacid']));
            $sql = "select * from " . tablename("zh_gjhdbm_attestation") . " WHERE id=:id  ";
            $list = pdo_fetch($sql, array(':id' => $_GET['rz_id']));
            $str = $list['type'] == 1 ? '个人认证' : '企业认证';
            $time = date('Y-m-d H:i', $list['rz_time']);
            $str2 = '申请提交成功,待管理员审核';
            //下面是要填充模板的信息
            $formwork = '{
    			"touser": "' . $_GET["openid"] . '",
    			"template_id": "' . $res["tid3"] . '",
    			"form_id":"' . $_GET['form_id'] . '",
    			"data": {
    				"keyword1": {
    					"value": "' . $str . '",
    					"color": "#173177"
    				},
    				"keyword2": {
    					"value": "' . $time . '",
    					"color": "#173177"
    				},
    				"keyword3": {
    					"value": "' . $str2 . '",
    					"color": "#173177"
    				}      	       		
    			}
    		}';
            $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" . $access_token . "";
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $formwork);
            $data = curl_exec($ch);
            curl_close($ch);
            return $data;
        }

        echo set_msg($_W);
    }





//活动海报的生成
    //活动二维码
    public function doPageHdPoster()
    {
        global $_W, $_GPC;
        function getCoade($activity_id)
        {
            function getaccess_token()
            {
                global $_W, $_GPC;
                $res = pdo_get('zh_gjhdbm_system', array('uniacid' => $_W['uniacid']));
                $appid = $res['appid'];
                $secret = $res['appsecret'];
                // $appid='wx80fa1d36c435231a';
                // $secret='9bb4735bd092f092477049bfd7e183f8';
                $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret . "";
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                $data = curl_exec($ch);
                curl_close($ch);
                $data = json_decode($data, true);
                return $data['access_token'];
            }

            function set_msg($activity_id)
            {
                $access_token = getaccess_token();
                $data2 = array(
                    "scene" => $activity_id,
                    "page" => "zh_gjhdbm/pages/activeinfo/activeinfo",
                    "width" => 100
                );
                $data2 = json_encode($data2);
                $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" . $access_token . "";
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $data2);
                $data = curl_exec($ch);
                curl_close($ch);
                return $data;
            }

            $img = set_msg($activity_id);
            $img = base64_encode($img);
            return $img;
        }

        $base64_image_content = "data:image/jpeg;base64," . getCoade($_GPC['id']);
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)) {
            $type = $result[2];
            $new_file = IA_ROOT . "/addons/zh_gjhdbm/img/";
            if (!file_exists($new_file)) {
                //检查是否有该文件夹，如果没有就创建，并给予最高权限
                mkdir($new_file, 0777);
            }
            $wname = "{$_GPC['activity_id']}" . ".{$type}";
            //$wname="1511.jpeg";
            $new_file = $new_file . $wname;
            file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)));
        }
        echo "/addons/zh_gjhdbm/img/" . $wname;

    }


//添加城市
    public function doPageSaveCity()
    {
        global $_GPC, $_W;
        $rst = pdo_get('zh_gjhdbm_city', array('cityname' => $_GPC['cityname']));
        if (!$rst) {
            $data['cityname'] = $_GPC['cityname'];
            $data['time'] = time();
            $data['uniacid'] = $_W['uniacid'];
            $res = pdo_insert('zh_gjhdbm_city', $data);
            if ($res) {
                echo '1';
            } else {
                echo '2';
            }
        }

    }




// public function doPageUpload(){
// 	global $_W, $_GPC;
// 	$qi=pdo_get('zh_gjhdbm_qiniu',array('uniacid'=>$_W['uniacid']));
// 	$uptypes=array(
// 		'image/jpg',
// 		'image/jpeg',
// 		'image/png',
// 		'image/pjpeg',
// 		'image/gif',
// 		'image/bmp',
// 		'image/x-png'
// 		);
// 	$Accesskey=$qi['accesskey'];
// 	$Secretkey=$qi['secretkey'];
// 	$Bucket=$qi['bucket'];
// 	$type=$qi['is_open'];
// 	$auto_delete_local = true;
//     $max_file_size=2000000;     //上传文件大小限制, 单位BYTE
//     $destination_folder="../attachment/"; //上传文件路径
//     if (!is_uploaded_file($_FILES["upfile"]['tmp_name']))
//     //是否存在文件
//     {
//     	echo "图片不存在!";
//     	exit;
//     }
//     $file = $_FILES["upfile"];
//     if($max_file_size < $file["size"])
//     //检查文件大小
//     {
//     	echo "文件太大!";
//     	exit;
//     }
//     if(!in_array($file["type"], $uptypes))
//     //检查文件类型
//     {
//     	echo "文件类型不符!".$file["type"];
//     	exit;
//     }

//     function file_delete($file) {
//     	if (empty($file)) {
//     		return false;
//     	}
//     	if (file_exists($file)) {
//     		@unlink($file);
//     	}
//     	if (file_exists(ATTACHMENT_ROOT . '/' . $file)) {
//     		@unlink(ATTACHMENT_ROOT . '/' . $file);
//     	}
//     	return true;
//     }
//     $filename=$file["tmp_name"];
//     $image_size = getimagesize($filename);
//     $pinfo=pathinfo($file["name"]);
//     $ftype=$pinfo['extension'];
//     $destination = $destination_folder.str_shuffle(time().rand(111111,999999)).".".$ftype;
//     if (file_exists($destination) && $overwrite != true)
//     {
//     	echo "同名文件已经存在了";
//     	exit;
//     }
//     if(!move_uploaded_file ($filename, $destination))
//     {
//     	echo "移动文件出错";
//     	exit;
//     }
//     $pinfo=pathinfo($destination);
//     $filename=$pinfo['basename'];
//     if($type==1){

//     load()->library('qiniu');
//     $auth = new Qiniu\Auth($Accesskey, $Secretkey);
//     $config = new Qiniu\Config();
//     $uploadmgr = new Qiniu\Storage\UploadManager($config);
//     $uploadtoken = $auth->uploadToken($Bucket, $filename, 3600);
//     list($ret, $err) = $uploadmgr->putFile($uploadtoken, $filename, ATTACHMENT_ROOT . '/' . $filename);
//     if ($auto_delete_local) {
//     	file_delete($filename);
//     }
//     if ($err !== null) {
//     	return error(1, '远程附件上传失败，请检查配置并重新上传');
//     } else {
//     	return $filename;
//     }
// }else{
// 	return $filename;
// }
// }


///////////////////以下分销


//分销设置
    public function doPageGetFxSet()
    {
        global $_W, $_GPC;
        $res = pdo_get('zh_gjhdbm_fxset', array('uniacid' => $_W['uniacid']));
        echo json_encode($res);
    }

//申请分销商
    public function doPageDistribution()
    {
        global $_W, $_GPC;
        pdo_delete('zh_gjhdbm_distribution', array('user_id' => $_GPC['user_id']));
        $set = pdo_get('zh_gjhdbm_fxset', array('uniacid' => $_W['uniacid']));
        $data['user_id'] = $_GPC['user_id'];
        $data['user_name'] = $_GPC['user_name'];
        $data['user_tel'] = $_GPC['user_tel'];
        $data['time'] = time();
        if ($set['is_fx'] == 1) {
            $data['state'] = 1;
        } else {
            $data['state'] = 2;
        }
        $data['uniacid'] = $_W['uniacid'];
        $res = pdo_insert('zh_gjhdbm_distribution', $data);
        $sq_id = pdo_insertid();
        if ($res) {
            $fx = pdo_get('zh_gjhdbm_fxuser', array('fx_user' => $_GPC['user_id']));
            if ($set['is_fx'] == 1 and !$fx) {
                pdo_insert("zh_gjhdbm_fxuser", array('user_id' => 0, 'fx_user' => $_GPC['user_id'], 'time' => time()));
            }
            echo $sq_id;
        } else {
            echo '申请失败!';
        }
    }

    //查看我的上线
    public function doPageMySx()
    {
        global $_W, $_GPC;
        $sql = "select a.* ,b.name from " . tablename("zh_gjhdbm_fxuser") . " a" . " left join " . tablename("zh_gjhdbm_user") . " b on b.id=a.user_id   WHERE a.fx_user=:fx_user ";
        $res = pdo_fetch($sql, array(':fx_user' => $_GPC['user_id']));
        echo json_encode($res);
    }


    //查看我的申请
    public function doPageMyDistribution()
    {
        global $_W, $_GPC;
        $res = pdo_get('zh_gjhdbm_distribution', array('user_id' => $_GPC['user_id']));
        echo json_encode($res);
    }


//绑定分销商
    public function doPageBinding()
    {
        global $_W, $_GPC;
        $res = pdo_get('zh_gjhdbm_fxuser', array('fx_user' => $_GPC['fx_user']));//已绑定
        $res2 = pdo_get('zh_gjhdbm_fxuser', array('user_id' => $_GPC['fx_user'], 'fx_user' => $_GPC['user_id']));//已绑定成下线
        if ($_GPC['user_id'] == $_GPC['fx_user']) {
            echo '自己不能绑定自己';
        } elseif ($res || $res2) {
            echo '不能重复绑定';
        } else {
            $res3 = pdo_insert('zh_gjhdbm_fxuser', array('user_id' => $_GPC['user_id'], 'fx_user' => $_GPC['fx_user'], 'time' => time()));
            if ($res3) {
                echo '1';
            } else {
                echo '2';
            }
        }

    }


//我的二维码
    public function doPageMyCode()
    {
        global $_W, $_GPC;
        function getCoade($user_id)
        {
            function getaccess_token()
            {
                global $_W, $_GPC;
                $res = pdo_get('zh_gjhdbm_system', array('uniacid' => $_W['uniacid']));
                $appid = $res['appid'];
                $secret = $res['appsecret'];
                //  $appid="wx80fa1d36c435231a";
                // $secret="9bb4735bd092f092477049bfd7e183f8";
                $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret . "";
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                $data = curl_exec($ch);
                curl_close($ch);
                $data = json_decode($data, true);
                return $data['access_token'];
            }

            function set_msg($user_id)
            {
                $access_token = getaccess_token();
                $data2 = array(
                    "scene" => $user_id,
                    // /"page"=>"zh_dianc/pages/info/info",
                    "width" => 100
                );
                $data2 = json_encode($data2);
                $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" . $access_token . "";
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $data2);
                $data = curl_exec($ch);
                curl_close($ch);
                return $data;
            }

            $img = set_msg($user_id);
            $img = base64_encode($img);
            return $img;
        }

        echo getCoade($_GPC['user_id']);

    }


//查看我的团队
    public function doPageMyTeam()
    {
        global $_W, $_GPC;
        $sql = "select a.* ,b.name ,b.img from " . tablename("zh_gjhdbm_fxuser") . " a" . " left join " . tablename("zh_gjhdbm_user") . " b on b.id=a.fx_user   WHERE a.user_id=:user_id order by id DESC";
        $res = pdo_fetchall($sql, array(':user_id' => $_GPC['user_id']));
        $res2 = array();
        for ($i = 0; $i < count($res); $i++) {
            $sql2 = "select a.* ,b.name ,b.img from " . tablename("zh_gjhdbm_fxuser") . " a" . " left join " . tablename("zh_gjhdbm_user") . " b on b.id=a.fx_user   WHERE a.user_id=:user_id order by id DESC";
            $res3 = pdo_fetchall($sql2, array(':user_id' => $res[$i]['fx_user']));
            $res2[] = $res3;

        }
        $res4 = array();
        for ($k = 0; $k < count($res2); $k++) {
            for ($j = 0; $j < count($res2[$k]); $j++) {
                $res4[] = $res2[$k][$j];
            }

        }
        $data['one'] = $res;
        $data['two'] = $res4;
        echo json_encode($data);
    }

//佣金统计
    public function doPageCountCommission()
    {
        global $_W, $_GPC;
        $sql2 = "select sum(case when state=1 then money else 0 end ) as dj ,sum( case when state=2 then money else 0 end ) as yx from  " . tablename('zh_gjhdbm_earnings') . " where uniacid=:uniacid  and user_id=:user_id ";
        //echo $sql2;die;
        $money = pdo_fetch($sql2, array('uniacid' => $_W['uniacid'], ':user_id' => $_GPC['user_id']));
        $sql3 = " select sum(tx_cost) as tx_money from " . tablename('zh_gjhdbm_commission_withdrawal') . " where  user_id=:user_id and state in (1,2)";
        $ytx_money = pdo_fetch($sql3, array(':user_id' => $_GPC['user_id']));
        $commission['ktx'] = number_format($money['yx'], 2) - number_format($ytx_money['tx_money'], 2);
        $commission['dj'] = number_format($money['dj'], 2);
        $commission['ytx'] = number_format($ytx_money['tx_money'], 2);
        $commission['lj'] = number_format($money['yx'], 2) + number_format($commission['dj'], 2);
        echo json_encode($commission);
    }

//佣金明细
    public function doPageYjlist()
    {
        global $_GPC, $_W;
        $pageindex = max(1, intval($_GPC['page']));
        $pagesize = 30;
        $data[':user_id'] = $_GPC['user_id'];
        $sql = "  select id,money,note,time from " . tablename('zh_gjhdbm_earnings') . " where user_id=:user_id and state=2  union all select id,tx_cost as money ,note,time from" . tablename('zh_gjhdbm_commission_withdrawal') . " where user_id=:user_id order by time desc";
        $select_sql = $sql . " LIMIT " . ($pageindex - 1) * $pagesize . "," . $pagesize;
        $list = pdo_fetchall($sql, $data);
        echo json_encode($list);

    }

//佣金提现设置
    public function doPageGetYjTxSet()
    {
        global $_GPC, $_W;
        $res = pdo_get('zh_gjhdbm_fxtxset', array('uniacid' => $_W['uniacid']));
        echo json_encode($res);
    }

//佣金提现
    public function doPageYjtx()
    {
        global $_W, $_GPC;
        $data['tx_cost'] = $_GPC['tx_cost'];
        $data['sj_cost'] = $_GPC['sj_cost'];
        $data['account'] = $_GPC['account'];
        $data['user_name'] = $_GPC['user_name'];
        $data['state'] = 1;
        $data['time'] = time();
        $data['uniacid'] = $_W['uniacid'];
        $data['user_id'] = $_GPC['user_id'];
        $data['note'] = '提现';
        $res = pdo_insert('zh_gjhdbm_commission_withdrawal', $data);
        if ($res) {
            echo '1';
        } else {
            echo '2';
        }
    }


///////////////////////////////////


}